Java and word document

A Word file is supposed to be created without Word with the help of Java application protocol interfaces.

Concepts Involved: Apache POI and Maven

Apache POI Is an API provided by Apache foundation which is a collection of different java libraries. This facility gives the library to read, write, and manipulate different Microsoft files such as Excel sheets, PowerPoint, and Word files. There are two types basically older version including ‘.doc’, ‘.ppt’ while newer versions of files as ‘.docx’, ‘.pptx’. There are two ways to deal with Apache POI as mentioned below:

Binary Distribution  Source Distribution 
No compilation is required to generate file.jar files  Files to generated needs to be compiled in order to generate file.jar files 
If working with Linux go for the ‘.tar.gz’ version (version 3.5 backward) otherwise simply download the .zip. the file extension for installation to work on Apache POI.  Here format does not matter because file is not compiled so can be altered as per need 

Here zip file is taken for consideration and also if the operating system is Windows, zip files should be preferred. It is a simple java project so binary distribution API is used. In the process of creating the document, several paragraphs will be inserted as a sample to display output and will be providing styles to paragraphs such as font color, font name, and font size. 

Now in order to create a Word file without using Microsoft Word, there is a java interface called Spire and if there is a need to create a PDF document without using Adobe Acrobat then it can be done with the use of an interface known as ‘E-Ice blue’. Here ‘Spire.doc’ must have to be imported as per problem statement as all dealing is in word format.

Spire.Doc for Java is a professional Java Word API that enables Java applications to create, convert, manipulate, and print Word documents without using Microsoft Office. It will be imported as a reference for this program as a reference. 

Syntax: For importing libraries in java of Spire

import Spire.Doc.jar ;

Components Of Spire involved are as follows:

Component Responsibility
XML Word Processor Format (XWPF) Reading and writing in ‘docx’ extensions files of MS-Word
Horrible Word Processor Format (HWPF) Reading and writing in ‘doc’ extensions files of MS-Word 

Additionally, there is another Java API for PDF format as discussed above ‘E-Ice Blue’ that enables developers to read, write, convert, and print PDF documents in Java applications without using Adobe Acrobat. Similarly, a PowerPoint API allows developers to create, read, edit, convert, and print PowerPoint files within Java applications.

If user is creating shear Maven project, one can easily add the jar dependency by adding the following configurations to the pom.xml.

Now, just like any class Apache POI contains classes and methods to work on. Major components of Apache POI are discussed below to understand the internal working of a file, how it is been generated without Word with help of classes and methods. There are basically two versions of files been present in Word itself.

Older files extensions Newer file extension (Version 3.5)
doc docx 
xls xlsx
ppt pptx

Maven 

These files are accessed using Maven. Maven is a powerful project management tool that is based on POM (project object model). It is used for projects to build, dependency, and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT.
In short terms we can tell maven is a tool that can be used for building and managing any Java-based project. Maven makes the day-to-day work of Java developers easier and generally help with the comprehension of any Java-based project.

Maven does have some specific commands to deal with files. Most frequently used are:

poi + poi + scratchpadpoi    // In order to deal with older Word file versions 
poi + poi-ooxml              // In order to deal with new Word file versions

Implementation: Below program depicts the responsibility of Spire API in creating a Word file:

Java

import com.spire.doc.Document;

import com.spire.doc.FileFormat;

import com.spire.doc.Section;

import com.spire.doc.documents.BuiltinStyle;

import com.spire.doc.documents.Paragraph;

import com.spire.doc.documents.ParagraphStyle;

class GFG {

    public static void main(String[] args)

    {

        Document document = new Document();

        Section section = document.addSection();

        Paragraph heading = section.addParagraph();

        heading.appendText("Java");

        Paragraph subheading_1 = section.addParagraph();

        subheading_1.appendText("What's Java");

        Paragraph para_1 = section.addParagraph();

        para_1.appendText(

            "Java is a general purpose, high-level programming language developed by Sun Microsystems."

            + " The Java programming language was developed by a small team of engineers, "

            + "known as the Green Team, who initiated the language in 1991.");

        Paragraph para_2 = section.addParagraph();

        para_2.appendText(

            "Originally called OAK, the Java language was designed for handheld devices and set-top boxes. "

            + "Oak was unsuccessful and in 1995 Sun changed the name to Java and modified the language to take "

            + "advantage of the burgeoning World Wide Web. ");

        Paragraph subheading_2 = section.addParagraph();

        subheading_2.appendText("Java Today");

        Paragraph para_3 = section.addParagraph();

        para_3.appendText(

            "Today the Java platform is a commonly used foundation for developing and delivering content "

            + "on the web. According to Oracle, there are more than 9 million Java developers worldwide and more "

            + "than 3 billion mobile phones run Java.");

        heading.applyStyle(BuiltinStyle.Title);

        subheading_1.applyStyle(BuiltinStyle.Heading_3);

        subheading_2.applyStyle(BuiltinStyle.Heading_3);

        ParagraphStyle style = new ParagraphStyle(document);

        style.setName("paraStyle");

        style.getCharacterFormat().setFontName("Arial");

        style.getCharacterFormat().setFontSize(11f);

        document.getStyles().add(style);

        para_1.applyStyle("paraStyle");

        para_2.applyStyle("paraStyle");

        para_3.applyStyle("paraStyle");

        for (int i = 0;

             i < section.getParagraphs().getCount(); i++) {

            section.getParagraphs()

                .get(i)

                .getFormat()

                .setAfterAutoSpacing(true);

        }

        document.saveToFile(

            "output/CreateAWordDocument.docx",

            FileFormat.Docx);

    }

}

Output:

Introduction

Word document is one of the most commonly used file types in our daily work, while create and read Word document are the most popular requirements when working with Word document. In this article, we’ll learn how to create a word document and read the text content in the Word document programmatically in java.

The Word Processing Library We Need

Free Spire.Doc for Java

Create a Word document

In Free Spire.Doc for Java, a Document object represents a Word document. The below code example shows how to create a Document object, add paragraphs, set paragraph styles and save the document object to file using Free Spire.Doc for Java.

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;

public class CreateWordDocument {
    public static void main(String[] args){
        //Create a Document instance
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

       //Add 3 paragraphs to the section
        Paragraph para1 = section.addParagraph();
        para1.appendText("Microsoft Word");

        Paragraph para2 = section.addParagraph();
        para2.appendText("Microsoft Word is a word processor developed by Microsoft. It was first released on October 25," +
                "1983 under the name Multi-Tool Word for Xenix systems. Subsequent versions were later written for several " +
                "other platforms including IBM PCs running DOS (1983), Apple Macintosh running the Classic Mac OS (1985)," +
                "AT&T Unix PC (1985), Atari ST (1988), OS/2 (1989), Microsoft Windows (1989), SCO Unix (1994), "+
                "and Mac OS (formerly OS X; 2001).");

        Paragraph para3 = section.addParagraph();
        para3.appendText("Commercial versions of Word are licensed as a standalone product or as a component of Microsoft Office, " +
                        "Windows RT or the discontinued Microsoft Works suite. Microsoft Word Viewer and Office Online are freeware editions "+
                        "of Word with limited features.");

        //Set title style for paragraph 1
        ParagraphStyle style1 = new ParagraphStyle(document);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);
        style1.getCharacterFormat().setTextColor(Color.BLUE);
        style1.getCharacterFormat().setFontName("Arial");
        style1.getCharacterFormat().setFontSize(12f);
        document.getStyles().add(style1);
        para1.applyStyle("titleStyle");

        //Set style for paragraph 2 and 3
        ParagraphStyle style2 = new ParagraphStyle(document);
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Arial");
        style2.getCharacterFormat().setFontSize(10f);
        document.getStyles().add(style2);
        para2.applyStyle("paraStyle");
        para3.applyStyle("paraStyle");

        //Horizontally align paragraph 1 to center
        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set indent for paragraph 2 and 3
        para2.getFormat().setFirstLineIndent(15f);
        para3.getFormat().setFirstLineIndent(15f);

        //Set spaces after paragraph 1 and 2
        para1.getFormat().setAfterSpacing(15f);
        para2.getFormat().setAfterSpacing(10f);

        //Save the document
        document.saveToFile("CreateWordDocument.docx", FileFormat.Docx);
    }
}

Create Word

Read Text Content in a Word document

Document class provides a getText() method which allows us to easily get the text content of a Word document.

import com.spire.doc.*;

public class TextReader {
    public static void main(String[] args){

        //Load the Word document
        Document doc = new Document("CreateWordDocument.docx");

        //Get text
        System.out.println(doc.getText());
    }
}

Read Word Document

Besides text, Free Spire.Doc for Java also supports to read a variety of other elements in a Word document, such as paragraph, image, header, footer, list and table. You can have a try by yourself.

package ua.com.prologistic;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import org.apache.poi.xwpf.usermodel.XWPFRun;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;

import java.io.FileOutputStream;

public class WordWorker {

    public static void main(String[] args) {

        try {

            // создаем модель docx документа,

            // к которой будем прикручивать наполнение (колонтитулы, текст)

            XWPFDocument docxModel = new XWPFDocument();

            CTSectPr ctSectPr = docxModel.getDocument().getBody().addNewSectPr();

            // получаем экземпляр XWPFHeaderFooterPolicy для работы с колонтитулами

            XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(docxModel, ctSectPr);

            // создаем верхний колонтитул Word файла

            CTP ctpHeaderModel = createHeaderModel(

            «Верхний колонтитул — создано с помощью Apache POI на Java :)»

            );

            // устанавливаем сформированный верхний

            // колонтитул в модель документа Word

            XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeaderModel, docxModel);

            headerFooterPolicy.createHeader(

                    XWPFHeaderFooterPolicy.DEFAULT,

                    new XWPFParagraph[]{headerParagraph}

            );

            // создаем нижний колонтитул docx файла

            CTP ctpFooterModel = createFooterModel(«Просто нижний колонтитул»);

            // устанавливаем сформированый нижний

            // колонтитул в модель документа Word

            XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooterModel, docxModel);

            headerFooterPolicy.createFooter(

                    XWPFHeaderFooterPolicy.DEFAULT,

                    new XWPFParagraph[]{footerParagraph}

            );

            // создаем обычный параграф, который будет расположен слева,

            // будет синим курсивом со шрифтом 25 размера

            XWPFParagraph bodyParagraph = docxModel.createParagraph();

            bodyParagraph.setAlignment(ParagraphAlignment.RIGHT);

            XWPFRun paragraphConfig = bodyParagraph.createRun();

            paragraphConfig.setItalic(true);

            paragraphConfig.setFontSize(25);

            // HEX цвет без решетки #

            paragraphConfig.setColor(«06357a»);

            paragraphConfig.setText(

            «Prologistic.com.ua — новые статьи по Java и Android каждую неделю. Подписывайтесь!»

            );

            // сохраняем модель docx документа в файл

            FileOutputStream outputStream = new FileOutputStream(«F:/Apache POI Word Test.docx»);

            docxModel.write(outputStream);

            outputStream.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        System.out.println(«Успешно записан в файл»);

    }

    private static CTP createFooterModel(String footerContent) {

        // создаем футер или нижний колонтитул

        CTP ctpFooterModel = CTP.Factory.newInstance();

        CTR ctrFooterModel = ctpFooterModel.addNewR();

        CTText cttFooter = ctrFooterModel.addNewT();

        cttFooter.setStringValue(footerContent);

        return ctpFooterModel;

    }

    private static CTP createHeaderModel(String headerContent) {

        // создаем хедер или верхний колонтитул

        CTP ctpHeaderModel = CTP.Factory.newInstance();

        CTR ctrHeaderModel = ctpHeaderModel.addNewR();

        CTText cttHeader = ctrHeaderModel.addNewT();

        cttHeader.setStringValue(headerContent);

        return ctpHeaderModel;

    }

}

Word documents have been widely used to create reports, quotations, invoices, etc. Generating Word documents automatically could save us lots of time and energy. This article will show you how to create a Word document on Java applications.

Add Spire.Doc.jar as a dependency

First of all, download Free Spire.Doc for Java 2.7.3. Unzip it, and you’ll get the jar file from the ‘lib’ folder. Then, create a Java application in your IDE. Import the jar file in your project as a dependency.

In the following sections, I will introduce how to insert different elements such as text, paragraphs, tables, lists and images, to a Word document.

Create a Word document

Usually, a large part of the content in a Word document is text. Firstly, we need to create a new instance of Document. And then add a section by Document.addSection() method and add a paragraph to the section by Section.addParagraph() method. After that, add text strings in paragraph by Paragraph.appendText(string text) method. We could also set the styles and format by ParagraphStyle. Finally, invoke document.saveToFile() method to save the document.

  1.   
  2. Document document = new Document();  
  3.   
  4.   
  5. Section section = document.addSection();  
  6.   
  7.   
  8. Paragraph para1 = section.addParagraph();  
  9. para1.appendText(«How to create Word document in Java»);  
  10.   
  11. Paragraph para2 = section.addParagraph();  
  12. para2.appendText(«This article demonstrate how to create Word document with text, images, lists and tables.»);  
  13.   
  14.   
  15. ParagraphStyle style1 = new ParagraphStyle(document);  
  16. style1.setName(«titleStyle»);  
  17. style1.getCharacterFormat().setBold(true);  
  18. style1.getCharacterFormat().setTextColor(Color.BLUE);  
  19. style1.getCharacterFormat().setFontName(«Arial»);  
  20. style1.getCharacterFormat().setFontSize(12f);  
  21. document.getStyles().add(style1);  
  22. para1.applyStyle(«titleStyle»);  
  23.   
  24.   
  25. ParagraphStyle style2 = new ParagraphStyle(document);  
  26. style2.setName(«paraStyle»);  
  27. style2.getCharacterFormat().setFontName(«Arial»);  
  28. style2.getCharacterFormat().setFontSize(11f);  
  29. document.getStyles().add(style2);  
  30. para2.applyStyle(«paraStyle»);  
  31.   
  32.   
  33.   
  34. para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);  
  35.   
  36.   
  37. para2.getFormat().setFirstLineIndent(12f);  
  38.   
  39.   
  40. para1.getFormat().setAfterSpacing(15f);  
  41. para2.getFormat().setAfterSpacing(10f);  
  42.   
  43.   
  44. document.saveToFile(«Output.docx», FileFormat.Docx);  

Output

How To Generate Word Documents In Java

Create a table in Word

Table sets text into rows and columns, which makes the text easy to edit and check. Spire.Doc for Java offers a method section.addTable() to add tables to the Word document. We can use Table.resetCells(int rowsNum, int columnsNum) method to set row and column numbers.

  1.   
  2. Document document = new Document();  
  3.   
  4.   
  5. Section section = document.addSection();  
  6.   
  7.   
  8. String[] header = {«Name»«Gender»};  
  9. String[][] data =  
  10.         {  
  11.                 new String[]{«Winny»«Female»},  
  12.                 new String[]{«Lois»«Female»},  
  13.                 new String[]{«Jois»«Female»},  
  14.                 new String[]{«Moon»«Male»},  
  15.                 new String[]{«Vinit»«Female»},  
  16.         };  
  17.   
  18.   
  19. Table table = section.addTable();  
  20. table.resetCells(data.length + 1, header.length);  
  21. table.applyStyle(DefaultTableStyle.Colorful_List);  
  22. table.getTableFormat().getBorders().setBorderType(BorderStyle.Single);  
  23.   
  24.   
  25. TableRow row = table.getRows().get(0);  
  26. row.isHeader(true);  
  27. row.setHeight(20);  
  28. row.setHeightType(TableRowHeightType.Exactly);  
  29. row.getRowFormat().setBackColor(Color.gray);  
  30. for (int i = 0; i < header.length; i++) {  
  31.     row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);  
  32.     Paragraph p = row.getCells().get(i).addParagraph();  
  33.     p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);  
  34.     TextRange range1 = p.appendText(header[i]);  
  35.     range1.getCharacterFormat().setFontName(«Arial»);  
  36.     range1.getCharacterFormat().setFontSize(12f);  
  37.     range1.getCharacterFormat().setBold(true);  
  38. }  
  39.   
  40.   
  41. for (int r = 0; r < data.length; r++) {  
  42.     TableRow dataRow = table.getRows().get(r + 1);  
  43.     dataRow.setHeight(25);  
  44.     dataRow.setHeightType(TableRowHeightType.Exactly);  
  45.     dataRow.getRowFormat().setBackColor(Color.white);  
  46.     for (int c = 0; c < data[r].length; c++) {  
  47.         dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);  
  48.         TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);  
  49.         range2.getCharacterFormat().setFontName(«Arial»);  
  50.         range2.getCharacterFormat().setFontSize(10f);  
  51.     }  
  52. }  
  53.   
  54.   
  55. for (int j = 1; j < table.getRows().getCount(); j++) {  
  56.     if (j % 2 == 0) {  
  57.         TableRow row2 = table.getRows().get(j);  
  58.         for (int f = 0; f < row2.getCells().getCount(); f++) {  
  59.             row2.getCells().get(f).getCellFormat().setBackColor(new Color(173216230));  
  60.         }  
  61.     }  
  62. }  
  63.   
  64.   
  65. document.saveToFile(«CreateTable.docx», FileFormat.Docx_2013);  

Output

How To Generate Word Documents In Java

Create lists in Word

There are two kinds of lists in Word: bulleted lists and numbered lists. Spire.Doc for Java offers Paragraph.getListFormat().applyBulletStyle() method and Paragraph.getListFormat().applyNumberedStyle() method to add the bulleted list and numbered list to the Word document.

  1.   
  2. Document document = new Document();  
  3.   
  4. Section section = document.addSection();  
  5.   
  6. Paragraph paragraph1 = section.addParagraph();  
  7. paragraph1.appendText(«Bulleted List»);  
  8. paragraph1.applyStyle(BuiltinStyle.Heading_1);  
  9. Paragraph paragraph2 = section.addParagraph();  
  10. paragraph2.appendText(«Chapter 1»);  
  11. Paragraph paragraph3 = section.addParagraph();  
  12. paragraph3.appendText(«Chapter 2»);  
  13. Paragraph paragraph4 = section.addParagraph();  
  14. paragraph4.appendText(«Chapter 3»);  
  15. Paragraph paragraph5 = section.addParagraph();  
  16. paragraph5.appendText(«Numbered List»);  
  17. paragraph5.applyStyle(BuiltinStyle.Heading_1);  
  18. Paragraph paragraph6 = section.addParagraph();  
  19. paragraph6.appendText(«Chapter 1»);  
  20. Paragraph paragraph7 = section.addParagraph();  
  21. paragraph7.appendText(«Chapter 2»);  
  22. Paragraph paragraph8 = section.addParagraph();  
  23. paragraph8.appendText(«Chapter 3»);  
  24.   
  25. for(int i = 1; i < 4; i++){  
  26.     Paragraph para = section.getParagraphs().get(i);  
  27.     para.getListFormat().applyBulletStyle();  
  28.     para.getListFormat().getCurrentListLevel().setNumberPosition(-10);  
  29. }  
  30.   
  31. for(int i = 5; i < 8; i++){  
  32.     Paragraph para = section.getParagraphs().get(i);  
  33.     para.getListFormat().applyNumberedStyle();  
  34.     para.getListFormat().getCurrentListLevel().setNumberPosition(-10);  
  35. }  
  36.   
  37. document.saveToFile(«CreateLists.docx», FileFormat.Docx_2013);  

Output

How To Generate Word Documents In Java

Add an image to Word

Images can beautify the document to attract more readers. Insertion of an image to Word documents can easily be done by using paragraph.appendPicture() method.

  1.   
  2.  Document document = new Document();  
  3.   
  4.    
  5.  Section section = document.addSection();  
  6.   
  7.    
  8.  Paragraph paragraph = section.addParagraph();  
  9.   
  10.    
  11.  DocPicture picture = paragraph.appendPicture(«Image.png»);  
  12.   
  13.    
  14.  picture.setWidth(300f);  
  15.  picture.setHeight(200f);  
  16.   
  17.    
  18.  document.saveToFile(«InsertImage.docx», FileFormat.Docx_2013);  

Output

How To Generate Word Documents In Java

Besides creating Word documents from scratch, Spire.Doc also supports to operate the existing Word documents, such as saving Word to PDF/image, adding digital signature to Word, etc. We will introduce more Word functions on Java platform in the future. Enjoy your reading!


1. Обзор

Apache POI

— это библиотека Java для работы с различными форматами файлов на основе стандартов Office Open XML (OOXML) и формата Microsoft OLE 2 Compound Document (OLE2).

В этом руководстве рассматривается поддержка

Apache POI для Microsoft Word

, наиболее часто используемого формата файлов Office. В нем рассматриваются шаги, необходимые для форматирования и создания файла MS Word, и способы синтаксического анализа этого файла.


2. Зависимости Maven

Единственная зависимость, которая требуется для Apache POI для обработки файлов MS Word:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>

Пожалуйста, нажмите

here

для последней версия этого артефакта.


3. Подготовка

Давайте теперь рассмотрим некоторые элементы, используемые для облегчения создания файла MS Word.


3.1. Файлы ресурсов

Мы соберем содержимое трех текстовых файлов и запишем их в файл MS Word с именем

rest-with-spring.docx

.

Кроме того, файл

logo-leaf.png

используется для вставки изображения в этот новый файл. Все эти файлы существуют в пути к классам и представлены несколькими статическими переменными:

public static String logo = "logo-leaf.png";
public static String paragraph1 = "poi-word-para1.txt";
public static String paragraph2 = "poi-word-para2.txt";
public static String paragraph3 = "poi-word-para3.txt";
public static String output = "rest-with-spring.docx";

Для тех, кому интересно, содержимое этих файлов ресурсов в репозитории, чья ссылка приведена в последнем разделе этого урока, извлечено из ссылки:/rest-with-spring-course? Utm__source = blog


3.2. Вспомогательный метод

Основной метод, состоящий из логики, используемой для создания файла MS Word, который описан в следующем разделе, использует вспомогательный метод:

public String convertTextFileToString(String fileName) {
    try (Stream<String> stream
      = Files.lines(Paths.get(ClassLoader.getSystemResource(fileName).toURI()))) {

        return stream.collect(Collectors.joining(" "));
    } catch (IOException | URISyntaxException e) {
        return null;
    }
}

Этот метод извлекает содержимое, содержащееся в текстовом файле, расположенном в пути к классам, имя которого является переданным аргументом

String

. Затем он объединяет строки в этом файле и возвращает присоединяющуюся

String

.


4. Создание файлов MS Word

В этом разделе приведены инструкции по форматированию и созданию файла Microsoft Word. Прежде чем работать с любой частью файла, нам нужно иметь экземпляр

XWPFDocument

XWPFDocument document = new XWPFDocument();


4.1. Форматирование заголовка и субтитров

Чтобы создать заголовок, нам нужно сначала создать экземпляр класса

XWPFParagraph

и установить выравнивание для нового объекта:

XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);

Содержимое абзаца должно быть заключено в объект

XWPFRun

.

Мы можем настроить этот объект, чтобы установить текстовое значение и связанные с ним стили:

XWPFRun titleRun = title.createRun();
titleRun.setText("Build Your REST API with Spring");
titleRun.setColor("009933");
titleRun.setBold(true);
titleRun.setFontFamily("Courier");
titleRun.setFontSize(20);

Нужно уметь определять цели set-методов из их имен.

Аналогичным образом мы создаем экземпляр

XWPFParagraph

, содержащий субтитры:

XWPFParagraph subTitle = document.createParagraph();
subTitle.setAlignment(ParagraphAlignment.CENTER);

Давайте также отформатируем субтитры:

XWPFRun subTitleRun = subTitle.createRun();
subTitleRun.setText("from HTTP fundamentals to API Mastery");
subTitleRun.setColor("00CC44");
subTitleRun.setFontFamily("Courier");
subTitleRun.setFontSize(16);
subTitleRun.setTextPosition(20);
subTitleRun.setUnderline(UnderlinePatterns.DOT__DOT__DASH);

Метод

setTextPosition

устанавливает расстояние между субтитрами и последующим изображением, а

setUnderline

определяет шаблон подчеркивания.

Обратите внимание, что мы жестко закодировали содержимое заголовка и подзаголовка, так как эти операторы слишком короткие, чтобы оправдать использование вспомогательного метода.


4.2. Вставка изображения

Изображение также необходимо обернуть в экземпляр

XWPFParagraph

. Мы хотим, чтобы изображение располагалось по центру по горизонтали и помещалось под субтитрами, поэтому ниже приведенный выше код должен содержать следующий фрагмент:

XWPFParagraph image = document.createParagraph();
image.setAlignment(ParagraphAlignment.CENTER);

Вот как установить расстояние между этим изображением и текстом под ним:

XWPFRun imageRun = image.createRun();
imageRun.setTextPosition(20);

Изображение берется из файла на пути к классам, а затем вставляется в файл MS Word с указанными размерами:

Path imagePath = Paths.get(ClassLoader.getSystemResource(logo).toURI());
imageRun.addPicture(Files.newInputStream(imagePath),
  XWPFDocument.PICTURE__TYPE__PNG, imagePath.getFileName().toString(),
  Units.toEMU(50), Units.toEMU(50));


4.3. Форматирование абзацев

Вот как мы создаем первый абзац с содержимым, взятым из файла

poi-word-para1.txt

:

XWPFParagraph para1 = document.createParagraph();
para1.setAlignment(ParagraphAlignment.BOTH);
String string1 = convertTextFileToString(paragraph1);
XWPFRun para1Run = para1.createRun();
para1Run.setText(string1);

Очевидно, что создание абзаца похоже на создание заголовка или подзаголовка. Единственным отличием здесь является использование вспомогательного метода вместо жестко закодированных строк.

Аналогичным образом мы можем создать два других абзаца, используя содержимое файлов

poi-word-para2.txt

и

poi-word-para3.txt

:

XWPFParagraph para2 = document.createParagraph();
para2.setAlignment(ParagraphAlignment.RIGHT);
String string2 = convertTextFileToString(paragraph2);
XWPFRun para2Run = para2.createRun();
para2Run.setText(string2);
para2Run.setItalic(true);

XWPFParagraph para3 = document.createParagraph();
para3.setAlignment(ParagraphAlignment.LEFT);
String string3 = convertTextFileToString(paragraph3);
XWPFRun para3Run = para3.createRun();
para3Run.setText(string3);

Создание этих трех абзацев практически одинаково, за исключением некоторых стилей, таких как выравнивание или курсив.


4.4. Создание файла MS Word

Теперь мы готовы записать файл Microsoft Word в память из переменной

document

:

FileOutputStream out = new FileOutputStream(output);
document.write(out);
out.close();
document.close();

Все фрагменты кода в этом разделе обернуты в метод с именем

handleSimpleDoc

.


5. Разбор и тестирование

В этом разделе описывается разбор файлов MS Word и проверка результата.


5.1. Подготовка

Мы объявляем статическое поле в тестовом классе:

static WordDocument wordDocument;

Это поле используется для ссылки на экземпляр класса, который включает в себя все фрагменты кода, показанные в разделах 3 и 4.

Перед анализом и тестированием нам нужно инициализировать статическую переменную, объявленную выше, и сгенерировать файл

rest-with-spring.docx

в текущем рабочем каталоге, вызвав метод

handleSimpleDoc

:

@BeforeClass
public static void generateMSWordFile() throws Exception {
    WordTest.wordDocument = new WordDocument();
    wordDocument.handleSimpleDoc();
}

Давайте перейдем к последнему шагу: анализ файла MS Word и проверка результата.


5.2. Разбор файла MS Word и проверка

Сначала мы извлекаем содержимое из указанного файла MS Word в каталоге проекта и сохраняем содержимое в

List

из

XWPFParagraph

:

Path msWordPath = Paths.get(WordDocument.output);
XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
List<XWPFParagraph> paragraphs = document.getParagraphs();
document.close();

Далее, давайте удостоверимся, что содержание и стиль заголовка такой же, как мы установили ранее:

XWPFParagraph title = paragraphs.get(0);
XWPFRun titleRun = title.getRuns().get(0);

assertEquals("Build Your REST API with Spring", title.getText());
assertEquals("009933", titleRun.getColor());
assertTrue(titleRun.isBold());
assertEquals("Courier", titleRun.getFontFamily());
assertEquals(20, titleRun.getFontSize());

Для простоты мы просто проверяем содержимое других частей файла, не используя стили. Проверка их стилей аналогична тому, что мы сделали с заголовком:

assertEquals("from HTTP fundamentals to API Mastery",
  paragraphs.get(1).getText());
assertEquals("What makes a good API?", paragraphs.get(3).getText());
assertEquals(wordDocument.convertTextFileToString
  (WordDocument.paragraph1), paragraphs.get(4).getText());
assertEquals(wordDocument.convertTextFileToString
  (WordDocument.paragraph2), paragraphs.get(5).getText());
assertEquals(wordDocument.convertTextFileToString
  (WordDocument.paragraph3), paragraphs.get(6).getText());

Теперь мы можем быть уверены, что создание файла

rest-with-spring.docx

прошло успешно.


6. Заключение

В этом руководстве была представлена ​​поддержка Apache POI для формата Microsoft Word. Он прошел шаги, необходимые для создания файла MS Word и проверки его содержимого.

Реализация всех этих примеров и фрагментов кода может быть найдена в

a проекте GitHub

.

Понравилась статья? Поделить с друзьями:
  • Java and excel files
  • Java and excel examples
  • Java and excel api
  • Jasperreports export to excel
  • Jasper report to excel