Java如何格式化word文件中的文字?

2019-10-16 22:27:14

在Java程式設計中,如何格式化word文件中的文字?

注意:需要存取網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裡下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並將全部.jar檔案匯入。

需要匯入全部包,如下圖所示 -

以下是格式化word文件中的文字的程式。

package com.yiibai;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class FormatTextInWord {
    public static void main(String[] args) throws Exception {

        // Blank Document
        XWPFDocument document = new XWPFDocument();

        // Write the Document in file system
        FileOutputStream out = new FileOutputStream(new File("fontstyle.docx"));

        // create paragraph
        XWPFParagraph paragraph = document.createParagraph();

        // Set Bold an Italic
        XWPFRun paragraphOneRunOne = paragraph.createRun();

        paragraphOneRunOne.setBold(true);
        paragraphOneRunOne.setItalic(true);
        paragraphOneRunOne.setText("Font Style");
        paragraphOneRunOne.addBreak();

        // Set text Position
        XWPFRun paragraphOneRunTwo = paragraph.createRun();

        paragraphOneRunTwo.setText("Font Style two");
        paragraphOneRunTwo.setTextPosition(100);

        // Set Strike through and Font Size and Subscript
        XWPFRun paragraphOneRunThree = paragraph.createRun();

        paragraphOneRunThree.setStrike(true);
        paragraphOneRunThree.setFontSize(20);
        paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
        paragraphOneRunThree.setText(" Different Font Styles");

        document.write(out);
        out.close();

        System.out.println("fontstyle.docx written successully");
    }
}

執行上面範例程式碼,得到以下結果 -

fontstyle.docx written successully

生成的World文件,得到以下結果 -