Apache POI Word - 快速指南

2021-10-29 16:04 更新

Apache POI Word - 概述

很多時候,需要一個軟件應用程序來生成Microsoft Word文件格式的參考文檔。 有時,應用程序甚至希望接收Word文件作為輸入數據。

任何想要生成MS-Office文件作為輸出的Java程序員都必須使用預定義和只讀API來執(zhí)行此操作。

什么是Apache POI?

Apache POI是一個流行的API,允許程序員使用Java程序創(chuàng)建,修改和顯示MS-Office文件。 它是由Apache Software Foundation開發(fā)和發(fā)布的一個開源庫,用于使用Java程序設計或修改MS-Office文件。 它包含用于將用戶輸入數據或文件解碼為MS-Office文檔的類和方法。

Apache POI的組件

Apache POI包含用于MS-Office的所有OLE2復合文檔的類和方法。 此API的組件列表如下:

  • POIFS(可疑混淆執(zhí)行文件系統(tǒng)):此組件是所有其他POI元素的基本因素。 它用于顯式讀取不同的文件。

  • HSSF(可怕的SpreadSheet格式):用于讀取和寫入.xls格式的MS-Excel文件。

  • XSSF(XML SpreadSheet格式):用于MS-Excel的.xlsx文件格式。

  • HPSF(可怕屬性集格式):用于提取MS-Office文件的屬性集。

  • HWPF(可怕字處理器格式):用于讀取和寫入MS-Word的.doc擴展文件。

  • XWPF(XML字處理器格式):用于讀取和寫入MS-Word的擴展文件 .docx 。

  • HSLF(可怕的幻燈片布局格式):用于閱讀,創(chuàng)建和編輯PowerPoint演示文稿。

  • HDGF(Horrible DiaGram格式):它包含MS-Visio二進制文件的類和方法。

  • HPBF(Horrible PuBlisher格式):用于讀取和寫入MS-Publisher文件。

本教程將指導您完成使用Java處理MS-Word文件的過程。 因此,討論僅限于HWPF和XWPF組件。

Apache POI Word - 安裝

本章將介紹在基于Windows和Linux的系統(tǒng)上設置Apache POI的過程。 Apache POI可以輕松地安裝和與您當前的Java環(huán)境集成,遵循幾個簡單的步驟,沒有任何復雜的設置過程。 在安裝時需要用戶管理。

系統(tǒng)要求

JDKJava SE 2 JDK 1.5或更高版本
內存1 GB RAM(推薦)
磁盤空間無最低要求
操作系統(tǒng)版本Windows XP或以上版本,Linux

現在讓我們繼續(xù)安裝Apache POI的步驟。

步驟1:驗證Java安裝

首先,您需要在系統(tǒng)上安裝Java軟件開發(fā)工具包(SDK)。 要驗證這一點,請執(zhí)行以下兩個命令中的任何一個,具體取決于您正在使用的平臺。

如果Java安裝已正確完成,那么它將顯示Java安裝的當前版本和規(guī)范。 下表給出了樣本輸出:

平臺命令示例輸出
Windows

打開命令控制臺并鍵入:

\> java -version

Java版本“1.7.0_60"

Java(TM)SE運行環(huán)境(版本1.7.0_60-b19)

Java熱點(TM)64位服務器VM(構建24.60-b09,混合模式)

Linux

打開命令終端并鍵入:

$ java -version

java版本“1.7.0_25"

打開JDK運行時環(huán)境(rhel-2.3.10.4.el6_4-x86_64)

打開JDK 64位服務器虛擬機(構建23.7-b01,混合模式)

步驟2:設置Java環(huán)境

將環(huán)境變量JAVA_HOME設置為指向計算機上安裝Java的基本目錄位置。 例如,

平臺描述
Windows將JAVA_HOME設置為C:\\ Program Files \\ java \\ jdk1.7.0_60
Linux導出JAVA_HOME = / usr / local / java-current

將Java編譯器位置的完整路徑附加到系統(tǒng)路徑。

描述描述
Windows將字符串“C:\\ Program Files \\ Java \\ jdk1.7.0_60 \\ bin"附加到系統(tǒng)變量PATH的結尾。
Linux導出PATH = $ PATH:$ JAVA_HOME / bin /

如上所述,從命令提示符處執(zhí)行命令 java - version

步驟3:安裝Apache POI庫

http://poi.apache.org/download下載最新版本的Apache POI。 html ,并將其內容解壓縮到一個文件夾,從中可以將所需的庫鏈接到Java程序。 讓我們假設文件收集在C驅動器上的文件夾中。

以下圖像顯示已下載文件夾中的目錄和文件結構:

將上述圖片中突出顯示的五個 jars 的完整路徑添加到CLASSPATH。

描述描述
Windows

將以下字符串附加到用戶變量CLASSPATH的結尾:

“C:\poi-3.9\poi-3.9-20121203.jar;"

“C:\poi-3.9\poi-ooxml-3.9-20121203.jar;"

“C:\poi-3.9\poi-ooxml-schemas-3.9-20121203.jar;"

“C:\poi-3.9\ooxml-lib\dom4j-1.6.1.jar;"

“C:\poi-3.9\ooxml-lib\xmlbeans-2.3.0.jar;.;"

Linux

導出CLASSPATH = $ CLASSPATH:

/usr/share/poi-3.9/poi-3.9-20121203.tar:

/usr/share/poi-3.9/poi-ooxml-schemas-3.9-20121203.tar:

/usr/share/poi-3.9/poi-ooxml-3.9-20121203.tar:

/usr/share/poi-3.9/ooxml-lib/dom4j-1.6.1.tar:

/usr/share/poi-3.9/ooxml-lib/xmlbeans-2.3.0.tar

Apache POI Word - 核心類

本章將介紹Apache POI用于管理Word文檔的類和方法。

文件

這是一個標記接口(接口不包含任何方法),它通知實現的類可以創(chuàng)建一個word文檔。

XWPF文檔

這是 org.apache.poi.xwpf.usermodel 包下的類。 它用于創(chuàng)建.docx文件格式的MS-Word文檔。

類方法:

S. No.方法和說明
1

commit()

提交并保存文檔。

2

createParagraph()

在本文檔中追加一個新段落。

3

createTable()

默認情況下,創(chuàng)建一個包含一行和一列的空表。

4

createTOC()

創(chuàng)建Word文檔的內容表。

5

getParagraphs()

返回包含頁眉或頁腳文本的段落。

6

getStyle()

返回使用的樣式對象。

對于此類的其余方法,請參考完整的API文檔:

https://poi.apache.org/apidocs/index.html?org/apache/poi/openxml4j/opc/internal/package-summary.html

XWPF段落

這是 org.apache.poi.xwpf.usermodel 包下的類,用于在Word文檔中創(chuàng)建段落。 此實例也用于將所有類型的元素添加到Word文檔中。

類方法:

S. No.方法和說明
1

createRun()

將新運行附加到此段落。

2

getAlignment()

返回將應用于本段文本的段落對齊方式。

3

setAlignment(ParagraphAlignment align)

指定應適用于本段文本的段落對齊方式。

4

setBorderBottom(邊框邊框)

指定應顯示在一組段落下方的邊框,這些段落具有相同的一組段落邊框設置。

5

setBorderLeft(邊框邊框)

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

6

setBorderRight(Borders border)

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

7

setBorderTop(邊框邊框)

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

對于此類的其余方法,請參考完整的API文檔:

https://poi.apache.org/apidocs/index.html?org/apache/poi/openxml4j/opc/internal/package-summary.html

XWPF運行

這是 org.apache.poi.xwpf.usermodel 包下的類,用于向段落中添加文本區(qū)域。

類方法:

S. No.方法和說明
1

addBreak()

指定中斷應放置在運行內容中的當前位置。

2

addTab()

指定制表符應放置在運行內容中的當前位置。

3

setColor(java.lang.String rgbStr)

設置文本顏色。

4

setFontSize(int size)

指定在顯示時應用于此運行內容中所有非復雜腳本字符的字體大小。

5

setText(java.lang.String value)

設置此文本運行的文本。

6

setBold(布爾值)

指定在文檔中顯示時,粗體屬性是否應用于此運行內容中的所有非復雜腳本字符。

對于此類的其余方法,請參考完整的API文檔:

https://poi.apache.org/apidocs/index.html?org/apache/poi/openxml4j/opc/internal/package-summary.html

XWPF樣式

這是 org.apache.poi.xwpf.usermodel 包下的類,用于向word文檔中的對象元素添加不同的樣式。

類方法:

S. No.方法和說明
1

getNextStyleID()

它用于獲取下一個樣式的StyleID。

2

getStyleId()

它用于獲取樣式的StyleID。

3

getStyles()

它用于獲取樣式。

4

setStyleId(java.lang.String styleId)

它用于設置styleID。

對于此類的其余方法,請參考完整的API文檔:

https://poi.apache.org/apidocs/index.html?org/apache/poi/openxml4j/opc/internal/package-summary.html

XWPF表格

這是 org.apache.poi.xwpf.usermodel 包下的類,用于將表數據添加到Word文檔中。

類方法:

S. No.方法和說明
1

addNewCol()

為此表中的每一行添加一個新列。

2

addRow(XWPFTableRow row,int pos)

addRow(XWPFTableRow row,int pos)...

3

createRow()

創(chuàng)建一個新的XWPFTableRow對象,其具有與那一刻定義的列數一樣多的單元格。

4

setWidth(int width)

設置列的寬度。

對于此類的其余方法,請參考完整的API文檔:
https://poi.apache.org/apidocs/index.html?org/apache/poi/openxml4j/opc/internal/package-summary.html

XWPF字符提取器

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

類方法:

S. No.方法和說明
1

getText()

檢索文檔中的所有文本。

對于此類的其余方法,請參考完整的API文檔:
https://poi.apache.org/apidocs/index.html?org/apache/poi/openxml4j/opc/internal/package-summary.html

Apache POI Word - 文檔

這里術語“document"是指MS-Word文件。 完成本章后,您將能夠使用Java程序創(chuàng)建新文檔并打開現有文檔。

創(chuàng)建空白文檔

以下簡單程序用于創(chuàng)建空白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 ,然后從命令提示符處編譯并執(zhí)行,如下所示:

$javac  CreateDocument.java
$java CreateDocument

如果您的系統(tǒng)環(huán)境配置了POI庫,它將編譯并執(zhí)行,以在當前目錄中生成名為 createdocument.docx 的空白Excel文件,并在命令提示符中顯示以下輸出:

createdocument.docx written successfully

Apache POI Word - 段落

在本章中,您將學習如何創(chuàng)建一個段落以及如何使用Java將其添加到文檔中。 段落是Word文件中頁面的一部分。

完成本章后,您將能夠創(chuàng)建一個段落并對其執(zhí)行讀取操作。

創(chuàng)建段落

首先,讓我們使用前面章節(jié)中討論的引用類創(chuàng)建一個段落。 按照前面的章節(jié),首先創(chuàng)建一個文檔,然后我們可以創(chuàng)建一個段落。

以下代碼段用于創(chuàng)建電子表格:

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

運行段落

您可以使用運行輸入文本或任何對象元素。 使用Paragraph實例,您可以創(chuàng)建運行。

以下代碼段用于創(chuàng)建運行。

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

它將編譯并執(zhí)行以在當前目錄中生成名為 createparagraph.docx 的Word文件,您將在命令提示符中獲得以下輸出:

createparagraph.docx written successfully

createparagraph.docx 文件如下所示。

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的文件中,從命令提示符處編譯并執(zhí)行它,如下所示:

$javac ApplyingBorder.java
$java ApplyingBorder

如果系統(tǒng)配置了POI庫,那么它將編譯并執(zhí)行,以在當前目錄中生成名為 appliedborder.docx 的Word文檔,并顯示以下輸出:

applyingborder.docx written successfully

appliedborder.docx 文件如下所示:

Apache POI Word - 表

在本章中,您將學習如何在文檔中創(chuàng)建數據表。 您可以使用 XWPFTable 類創(chuàng)建表數據。 將每個添加到表格中,并將單元格添加到,您將獲得表格數據。

創(chuàng)建表

以下代碼用于在文檔中創(chuàng)建表:

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的文件中。從命令提示符處編譯并執(zhí)行它,如下所示:

$javac CreateTable.java
$java CreateTable

它將在當前目錄中生成名為 createtable.docx 的Word文件,并在命令提示符下顯示以下輸出:

createtable.docx written successfully

createtable.docx 文件如下所示:

字體樣式和對齊方式

本章介紹如何使用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 ,然后從命令提示符處編譯并執(zhí)行它,如下所示:

$javac FontStyle.java
$java FontStyle

它將在當前目錄中生成名為 font style.docx 的Word文件,并在命令提示符下顯示以下輸出:

fontstyle.docx written successfully

fontstyle.docx 文件如下所示。

對齊方式

以下代碼用于設置與段落文本的對齊方式:

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 ,然后從命令提示符處編譯并執(zhí)行,如下所示:

$javac AlignParagraph.java
$java AlignParagraph

它將在當前目錄中生成名為 align paragraph.docx 的Word文件,并在命令提示符中顯示以下輸出:

alignparagraph.docx written successfully

alignparagraph.docx 文件如下所示:

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("create_paragraph.docx"));
   //using XWPFWordExtractor Class
   XWPFWordExtractor we = new XWPFWordExtractor(docx);
   System.out.println(we.getText());保存并閱讀
   }
}

將上述代碼保存為 WordExtractor.java。從命令提示符處編譯并執(zhí)行,如下所示:

$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.

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號