Apache POI Word 快速指南



Apache POI Word - 概述

很多時候,軟體應用程式需要生成Microsoft Word檔案格式的參考文件。有時,甚至期望應用程式接收Word檔案作為輸入資料。

任何想要生成MS-Office檔案作為輸出的Java程式設計師都必須使用預定義的只讀API來做到這一點。

什麼是Apache POI?

Apache POI是一個流行的API,它允許程式設計師使用Java程式建立、修改和顯示MS-Office檔案。它是一個開源庫,由Apache軟體基金會開發和分發,用於使用Java程式設計或修改MS-Office檔案。它包含用於將使用者輸入資料或檔案解碼為MS-Office文件的類和方法。

Apache POI的組成部分

Apache POI包含用於處理所有MS-Office的OLE2複合文件的類和方法。此API的元件列表如下所示:

  • POIFS(Poor Obfuscation Implementation File System) - 此元件是所有其他POI元素的基本因素。它用於顯式讀取不同的檔案。

  • HSSF(Horrible SpreadSheet Format) - 用於讀取和寫入MS-Excel檔案的.xls格式。

  • XSSF(XML SpreadSheet Format) - 用於MS-Excel的.xlsx檔案格式。

  • HPSF(Horrible Property Set Format) - 用於提取MS-Office檔案的屬性集。

  • HWPF(Horrible Word Processor Format) - 用於讀取和寫入MS-Word的.doc副檔名檔案。

  • XWPF(XML Word Processor Format) - 用於讀取和寫入MS-Word的.docx副檔名檔案。

  • HSLF(Horrible Slide Layout Format) - 用於讀取、建立和編輯PowerPoint簡報。

  • HDGF(Horrible DiaGram Format) - 包含用於MS-Visio二進位制檔案的類和方法。

  • HPBF(Horrible PuBlisher Format) - 用於讀取和寫入MS-Publisher檔案。

本教程指導您完成使用Java處理MS-Word檔案的過程。因此,討論僅限於HWPF和XWPF元件。

注意 - POI的舊版本支援諸如DOC、XLS、PPT等二進位制檔案格式。3.5及以上版本,POI支援MS-Office的OOXML檔案格式,如DOCX、XLSX、PPTX等。

Apache POI Word - 安裝

本章將引導您完成在基於Windows和Linux的系統上設定Apache POI的過程。Apache POI可以通過幾個簡單的步驟輕鬆安裝並與您當前的Java環境整合,無需任何複雜的設定過程。安裝過程中需要使用者管理。

系統要求

JDK Java SE 2 JDK 1.5或更高版本
記憶體 1 GB RAM(推薦)
磁碟空間 無最低要求
作業系統版本 Windows XP或更高版本,Linux

現在讓我們繼續介紹安裝Apache POI的步驟。

步驟1:驗證您的Java安裝

首先,您需要在系統上安裝Java軟體開發工具包(SDK)。要驗證這一點,請根據您正在使用的平臺執行以下兩個命令之一。

如果Java安裝已正確完成,則它將顯示您Java安裝的當前版本和規範。示例輸出在以下表格中給出。

平臺 命令 示例輸出
Windows

開啟命令控制檯並輸入:

\>java -version

java version "11.0.11" 2021-04-20 LTS

Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Linux

開啟命令終端並輸入:

$java -version

java version "11.0.11" 2021-04-20 LTS

Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)

步驟2:設定您的Java環境

設定環境變數JAVA_HOME以指向Java安裝在您計算機上的基本目錄位置。例如,

序號 平臺和描述
1

Windows

將JAVA_HOME設定為C:\ProgramFiles\java\jdk11.0.11

2

Linux

匯出JAVA_HOME = /usr/local/java-current

將Java編譯器位置的完整路徑附加到系統路徑。

序號 平臺和描述
1

Windows

將字串“C:\Program Files\Java\jdk11.0.11\bin”附加到系統變數PATH的末尾。

2

Linux

匯出PATH = $PATH:$JAVA_HOME/bin/

從命令提示符執行命令java -version,如上所述。

步驟3:安裝Apache POI庫

https://poi.apache.org/download.html下載最新版本的Apache POI,並將其內容解壓縮到一個資料夾中,以便可以將所需的庫連結到您的Java程式。假設檔案收集在C驅動器上的資料夾中。

將所需jars的完整路徑新增到CLASSPATH中,如下所示。

序號 平臺和描述
1

Windows

將以下字串附加到使用者變數的末尾

CLASSPATH -

C:\poi-bin-5.1.0\poi-5.1.0.jar;

C:\poi-bin-5.1.0\poi-ooxml-5.1.0.jar;

C:\poi-bin-5.1.0\poi-ooxml-full-5.1.0.jar;

C:\poi-bin-5.1.0\lib\commons-codec-1.15.jar;

C:\poi-bin-5.1.0\lib\commons-collections4-4.4.jar;

C:\poi-bin-5.1.0\lib\commons-io-2.11.0.jar;

C:\poi-bin-5.1.0\lib\commons-math3-3.6.1.jar;

C:\poi-bin-5.1.0\lib\log4j-api-2.14.1.jar;

C:\poi-bin-5.1.0\lib\SparseBitSet-1.2.jar;

C\poi-bin-5.1.0\ooxml-lib\commons-compress-1.21.jar

C\poi-bin-5.1.0\ooxml-lib\commons-logging-1.2.jar

C\poi-bin-5.1.0\ooxml-lib\curvesapi-1.06.jar

C\poi-bin-5.1.0\ooxml-lib\slf4j-api-1.7.32.jar

C\poi-bin-5.1.0\ooxml-lib\xmlbeans-5.0.2.jar

2

Linux

匯出CLASSPATH = $CLASSPATH

/usr/share/poi-bin-5.1.0/poi-5.1.0.jar.tar

/usr/share/poi-bin-5.1.0/poi-ooxml-5.1.0.tar

/usr/share/poi-bin-5.1.0/poi-ooxml-full-5.1.0.tar

/usr/share/poi-bin-5.1.0/lib/commons-codec-1.15.jar.tar

/usr/share/poi-bin-5.1.0/lib/commons-collections4-4.4.tar

/usr/share/poi-bin-5.1.0/lib/commons-io-2.11.0.tar

/usr/share/poi-bin-5.1.0/lib/commons-math3-3.6.1.tar

/usr/share/poi-bin-5.1.0/lib/log4j-api-2.14.1.tar

/usr/share/poi-bin-5.1.0/lib/SparseBitSet-1.2.tar

/usr/share/poi-bin-5.1.0/ooxml-lib/commons-compress-1.21.tar

/usr/share/poi-bin-5.1.0/ooxml-lib/commons-logging-1.2.tar

/usr/share/poi-bin-5.1.0/ooxml-lib/curvesapi-1.06.tar

/usr/share/poi-bin-5.1.0/ooxml-lib/slf4j-api-1.7.32.tar

/usr/share/poi-bin-5.1.0/ooxml-lib/xmlbeans-5.0.2.tar

Apache POI Word - 核心類

本章將引導您瞭解Apache POI用於管理Word文件的類和方法。

文件

這是一個標記介面(介面不包含任何方法),它通知實現的類能夠建立Word文件。

XWPFDocument

這是org.apache.poi.xwpf.usermodel包下的一個類。它用於建立具有.docx檔案格式的MS-Word文件。

類方法

序號 方法和描述
1

commit()

提交併儲存文件。

2

createParagraph()

將新段落附加到此文件。

3

createTable()

建立一個預設只有一行一列的空表格。

4

createTOC()

為Word文件建立目錄。

5

getParagraphs()

返回包含頁首或頁尾文字的段落。

6

getStyle()

返回使用的樣式物件。

有關此類的其餘方法,請參閱以下完整API文件:

包org.apache.poi.openxml4j.opc.internal.

XWPFParagraph

這是org.apache.poi.xwpf.usermodel包下的一個類,用於在Word文件中建立段落。此例項還用於將所有型別的元素新增到Word文件中。

類方法

序號 方法和描述
1

createRun()

將新的執行附加到此段落。

2

getAlignment()

返回將應用於此段落中文字的段落對齊方式。

3

setAlignment(ParagraphAlignment align)

指定將應用於此段落中文字的段落對齊方式。

4

setBorderBottom(Borders border)

指定將在具有相同段落邊框設定的一組段落下方顯示的邊框。

5

setBorderLeft(Borders border)

指定將在頁面左側圍繞指定段落顯示的邊框。

6

setBorderRight(Borders border)

指定將在頁面右側圍繞指定段落顯示的邊框。

7

setBorderTop(Borders border)

指定將在具有相同段落邊框設定的一組段落上方顯示的邊框。

有關此類的其餘方法,請參閱以下完整API文件:

POI API 文件

XWPFRun

這是org.apache.poi.xwpf.usermodel包下的一個類,用於向段落新增文字區域。

類方法

序號 方法和描述
1

addBreak()

指定應在執行內容的當前位置放置換行符。

2

addTab()

指定應在執行內容的當前位置放置製表符。

3

setColor(java.lang.String rgbStr)

設定文字顏色。

4

setFontSize(int size)

指定在顯示時應應用於此執行內容中所有非複雜指令碼字元的字型大小。

5

setText(java.lang.String value)

設定此文字執行的文字。

6

setBold(boolean value)

指定在文件中顯示時是否應將粗體屬性應用於此執行內容中所有非複雜指令碼字元。

有關此類的其餘方法,請參閱以下完整API文件:

POI API 文件

XWPFStyle

這是一個位於 **org.apache.poi.xwpf.usermodel** 包下的類,用於向 Word 文件中的物件元素新增不同的樣式。

類方法

序號 方法和描述
1

getNextStyleID()

用於獲取下一個樣式的 StyleID。

2

getStyleId()

用於獲取樣式的 StyleID。

3

getStyles()

用於獲取樣式。

4

setStyleId(java.lang.String styleId)

用於設定 styleID。

有關此類的其餘方法,請參閱以下完整API文件:

POI API 文件

XWPFTable

這是一個位於 **org.apache.poi.xwpf.usermodel** 包下的類,用於向 Word 文件中新增表格資料。

類方法

序號 方法和描述
1

addNewCol()

為該表格中的每一行新增一列。

2

addRow(XWPFTableRow row, int pos)

在位置 pos 處向表格新增新行。

3

createRow()

建立一個新的 XWPFTableRow 物件,該物件包含當前定義的列數的單元格。

4

setWidth(int width)

設定列的寬度。

有關此類的其餘方法,請參閱完整的 API 文件:− POI API 文件

XWPFWordExtractor

這是一個位於 **org.apache.poi.xwpf.extractor** 包下的類。它是一個基本的解析器類,用於從 Word 文件中提取簡單文字。

類方法

序號 方法和描述
1

getText()

檢索文件中的所有文字。

有關此類的其餘方法,請參閱完整的 API 文件:− POI API 文件

Apache POI Word - 文件

這裡“文件”指的是 MS-Word 檔案。完成本章後,您將能夠使用 Java 程式建立新文件和開啟現有文件。

建立空白文件

以下簡單程式用於建立空白的 MS-Word 文件:−

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class CreateDocument {
   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("createdocument.docx"));
      document.write(out);
      out.close();
      System.out.println("createdocument.docx written successully");
   }
}

將上述 Java 程式碼儲存為 **CreateDocument.java**,然後從命令提示符編譯並執行它,如下所示:−

$javac  CreateDocument.java
$java CreateDocument

如果您的系統環境已配置 POI 庫,它將編譯並執行以生成一個名為 **createdocument.docx** 的空白 Word 文件檔案,該檔案位於您的當前目錄中,並在命令提示符中顯示以下輸出:−

createdocument.docx written successfully

Apache POI Word - 段落

在本節中,您將學習如何建立段落以及如何使用 Java 將其新增到文件中。段落是 Word 檔案中頁面的一部分。

完成本章後,您將能夠建立段落並對其執行讀取操作。

建立段落

首先,讓我們使用前面章節中討論的引用類來建立一個段落。按照上一章的操作,先建立一個文件,然後我們就可以建立段落了。

以下程式碼片段用於建立電子表格:−

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

//Create a blank spreadsheet
XWPFParagraph paragraph = document.createParagraph();

在段落中執行

您可以使用 **Run** 輸入文字或任何物件元素。使用 Paragraph 例項,您可以建立 **run**。

以下程式碼片段用於建立 Run。

XWPFRun run = paragraph.createRun();

寫入段落

讓我們嘗試將一些文字輸入文件。考慮以下文字資料:−

At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose 
in the domains of Academics, Information Technology, Management and Computer Programming Languages.

以下程式碼用於將上述資料寫入段落。

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class CreateParagraph {
   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("createparagraph.docx"));
        
      //create Paragraph
      XWPFParagraph paragraph = document.createParagraph();
      XWPFRun run = paragraph.createRun();
      run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming Languages.");
			
      document.write(out);
      out.close();
      System.out.println("createparagraph.docx written successfully");
   }
}

將上述 Java 程式碼儲存為 **CreateParagraph.java**,然後從命令提示符編譯並執行它,如下所示:−

$javac CreateParagraph.java
$java CreateParagraph

它將編譯並執行以生成一個名為 **createparagraph.docx** 的 Word 檔案,該檔案位於您的當前目錄中,並且您將在命令提示符中獲得以下輸出:−

createparagraph.docx written successfully

**createparagraph.docx** 檔案如下所示。

Create Paragraph

Apache POI Word - 邊框

在本節中,您將學習如何使用 Java 程式設計為段落應用邊框。

應用邊框

以下程式碼用於在文件中應用邊框:−

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.Borders;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class ApplyingBorder {

   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("applyingborder.docx"));
        
      //create paragraph
      XWPFParagraph paragraph = document.createParagraph();
        
      //Set bottom border to paragraph
      paragraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        
      //Set left border to paragraph
      paragraph.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        
      //Set right border to paragraph
      paragraph.setBorderRight(Borders.BASIC_BLACK_DASHES);
        
      //Set top border to paragraph
      paragraph.setBorderTop(Borders.BASIC_BLACK_DASHES);
        
      XWPFRun run = paragraph.createRun();
         run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming " +
         "Languages.");
        
      document.write(out);
      out.close();
      System.out.println("applyingborder.docx written successully");
   }
}

將上述程式碼儲存在名為 **ApplyingBorder.java** 的檔案中,從命令提示符編譯並執行它,如下所示:−

$javac ApplyingBorder.java
$java ApplyingBorder

如果您的系統已配置 POI 庫,則它將編譯並執行以生成一個名為 **applyingborder.docx** 的 Word 文件,該檔案位於您的當前目錄中,並顯示以下輸出:−

applyingborder.docx written successfully

**applyingborder.docx** 檔案如下所示:−

Border Paragraph

Apache POI Word - 表格

在本節中,您將學習如何在文件中建立資料表格。您可以使用 **XWPFTable** 類建立表格資料。透過向表格新增每個 **Row** 並向 **Row** 新增每個 **cell**,您將獲得表格資料。

建立表格

以下程式碼用於在文件中建立表格:−

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class CreateTable {

   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("create_table.docx"));
        
      //create table
      XWPFTable table = document.createTable();
		
      //create first row
      XWPFTableRow tableRowOne = table.getRow(0);
      tableRowOne.getCell(0).setText("col one, row one");
      tableRowOne.addNewTableCell().setText("col two, row one");
      tableRowOne.addNewTableCell().setText("col three, row one");
		
      //create second row
      XWPFTableRow tableRowTwo = table.createRow();
      tableRowTwo.getCell(0).setText("col one, row two");
      tableRowTwo.getCell(1).setText("col two, row two");
      tableRowTwo.getCell(2).setText("col three, row two");
		
      //create third row
      XWPFTableRow tableRowThree = table.createRow();
      tableRowThree.getCell(0).setText("col one, row three");
      tableRowThree.getCell(1).setText("col two, row three");
      tableRowThree.getCell(2).setText("col three, row three");
	
      document.write(out);
      out.close();
      System.out.println("create_table.docx written successully");
   }
}

將上述程式碼儲存在名為 **CreateTable.java** 的檔案中。從命令提示符編譯並執行它,如下所示:−

$javac CreateTable.java
$java CreateTable

它將在您的當前目錄中生成一個名為 **createtable.docx** 的 Word 檔案,並在命令提示符中顯示以下輸出:−

createtable.docx written successfully

**createtable.docx** 檔案如下所示:−

Create Table

Apache POI Word - 字型和對齊

本章介紹如何使用 Java 在 Word 文件中應用不同的字型樣式和對齊方式。通常,字型樣式包括:字型大小、型別、粗體、斜體和下劃線。對齊方式分為左對齊、居中對齊、右對齊和兩端對齊。

字型樣式

以下程式碼用於設定不同的字型樣式:−

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 FontStyle {

   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.java**,然後從命令提示符編譯並執行它,如下所示:−

$javac FontStyle.java
$java FontStyle

它將在您的當前目錄中生成一個名為 **fontstyle.docx** 的 Word 檔案,並在命令提示符中顯示以下輸出:−

fontstyle.docx written successfully

**fontstyle.docx** 檔案如下所示。

Font Style

對齊方式

以下程式碼用於設定段落文字的對齊方式:−

import java.io.File;
import java.io.FileOutputStream;
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;

public class AlignParagraph {

   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("alignparagraph.docx"));
        
      //create paragraph
      XWPFParagraph paragraph = document.createParagraph();
        
      //Set alignment paragraph to RIGHT
      paragraph.setAlignment(ParagraphAlignment.RIGHT);
      XWPFRun run = paragraph.createRun();
      run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming " +
         "Languages.");
        
      //Create Another paragraph
      paragraph = document.createParagraph();
        
      //Set alignment paragraph to CENTER
      paragraph.setAlignment(ParagraphAlignment.CENTER);
      run = paragraph.createRun();
      run.setText("The endeavour started by Mohtashim, an AMU " +
         "alumni, who is the founder and the managing director " +
         "of Tutorials Point (I) Pvt. Ltd. He came up with the " +
         "website tutorialspoint.com in year 2006 with the help" +
         "of handpicked freelancers, with an array of tutorials" +
         " for computer programming languages. ");
			
      document.write(out);
      out.close();
      System.out.println("alignparagraph.docx written successfully");
   }
}

將上述程式碼儲存為 **AlignParagraph.java**,然後從命令提示符編譯並執行它,如下所示:−

$javac AlignParagraph.java
$java AlignParagraph

它將在您的當前目錄中生成一個名為 **alignparagraph.docx** 的 Word 檔案,並在命令提示符中顯示以下輸出:−

alignparagraph.docx written successfully

**alignparagraph.docx** 檔案如下所示:−

Align Paragraph

Apache POI Word - 文字提取

本章說明如何使用 Java 從 Word 文件中提取簡單的文字資料。如果您想從 Word 文件中提取元資料,請使用 Apache Tika。

對於 .docx 檔案,我們使用類 org.apache.poi.xwpf.extractor.XPFFWordExtractor 來提取並返回 Word 檔案中的簡單資料。同樣,我們還有不同的方法來提取 Word 檔案中的標題、腳註、表格資料等。

以下程式碼顯示瞭如何從 Word 檔案中提取簡單文字:−

import java.io.FileInputStream;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class WordExtractor {
   public static void main(String[] args)throws Exception {
      XWPFDocument docx = new XWPFDocument(new FileInputStream("createparagraph.docx"));
      
      //using XWPFWordExtractor Class
      XWPFWordExtractor we = new XWPFWordExtractor(docx);
      System.out.println(we.getText());
   }
}

將上述程式碼儲存為 **WordExtractor.java**。從命令提示符編譯並執行它,如下所示:−

$javac WordExtractor.java
$java WordExtractor

它將生成以下輸出:−

At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose
in the domains of Academics, Information Technology, Management and Computer Programming Languages.
廣告