Apache POI Word - 快速指南
Apache POI Word - Overview
很多时候,需要一个软件应用程序来生成Microsoft Word文件格式的参考文档。 有时,甚至希望应用程序接收Word文件作为输入数据。
任何想要生成MS-Office文件作为输出的Java程序员都必须使用预定义的只读API来执行此操作。
什么是Apache POI?
Apache POI是一种流行的API,允许程序员使用Java程序创建,修改和显示MS-Office文件。 它是由Apache Software Foundation开发和分发的开源库,用于使用Java程序设计或修改MS-Office文件。 它包含将用户输入数据或文件解码为MS-Office文档的类和方法。
Apache POI的组件
Apache POI包含用于处理MS-Office的所有OLE2复合文档的类和方法。 该API的组件列表如下 -
POIFS (Poor Obfuscation Implementation File System) - 该组件是所有其他POI元素的基本因素。 它用于显式读取不同的文件。
HSSF (Horrible SpreadSheet Format) - 用于读取和写入.xls格式的MS-Excel文件。
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组件。
Note - POI支持二进制文件格式的旧版本,如DOC,XLS,PPT等。 版本3.5 ONWARDS,POI支持MS-OFFICE的OOXML文件格式,如DOCX,XLSX,PPTX等。
Apache POI Word - Installation
本章将指导您完成在基于Windows和Linux的系统上设置Apache POI的过程。 Apache POI可以轻松安装并与您当前的Java环境集成,只需几个简单的步骤,无需任何复杂的设置过程。 安装时需要用户管理。
系统需求 (System Requirements)
JDK | Java SE 2 JDK 1.5或以上版本 |
Memory | 1 GB RAM(推荐) |
磁盘空间 | 没有最低要求 |
操作系统版本 | Windows XP或更高版本,Linux |
现在让我们继续安装Apache POI的步骤。
第1步:验证Java安装
首先,您需要在系统上安装Java软件开发工具包(SDK)。 要验证这一点,请执行下面提到的两个命令中的任何一个,具体取决于您正在使用的平台。
如果Java安装已正确完成,那么它将显示Java安装的当前版本和规范。 下表给出了一个示例输出 -
平台 | 命令 | 样本输出 |
---|---|---|
Windows | 打开命令控制台并输入 - \》java –version | Java版“1.7.0_60” Java(TM)SE运行时环境(版本1.7.0_60-b19) Java Hotspot(TM)64位服务器VM(内置24.60-b09,混合模式) |
Linux | 打开命令终端并输入 - $java –version | java版“1.7.0_25” 打开JDK运行时环境(rhel-2.3.10.4.el6_4-x86_64) 打开JDK 64位服务器VM(内置23.7-b01,混合模式) |
我们假设本教程的读者在其系统上安装了Java SDK版本1.7.0_60。
如果您没有Java SDK,请从https://www.oracle.com/technetwork/java/javase/downloads/index.html下载其当前版本并安装它。
第2步:设置Java环境
将环境变量JAVA_HOME设置为指向计算机上安装Java的基本目录位置。 例如,
平台 | 描述 |
---|---|
Windows | 将JAVA_HOME设置为C:\ProgramFiles\java\jdk1.7.0_60 |
Linux | 导出JAVA_HOME =/usr/local/java-current |
将Java编译器位置的完整路径附加到系统路径。
平台 | 描述 |
---|---|
Windows | 将字符串“C:\Program Files\Java\jdk1.7.0_60\bin”附加到系统变量PATH的末尾。 |
Linux | 导出PATH = $ PATH:$ JAVA_HOME/bin/ |
如上所述,从命令提示符执行命令java - version 。
第3步:安装Apache POI库
从https://poi.apache.org/download.html下载最新版本的Apache POI,并将其内容解压缩到一个文件夹,从该文件夹可以将所需的库链接到您的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-架构 - 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 - Core Classes
本章将向您介绍用于管理Word文档的Apache POI的类和方法。
Document
这是一个标记接口(接口不包含任何方法),通知实现的类可以创建word文档。
XWPFDocument
这是org.apache.poi.xwpf.usermodel包下的一个类。 它用于创建.docx文件格式的MS-Word文档。
类方法 (Class Methods)
Sr.No. | 方法和描述 |
---|---|
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文档中。
类方法 (Class Methods)
Sr.No. | 方法和描述 |
---|---|
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文档 -
XWPFRun
这是org.apache.poi.xwpf.usermodel包下的一个类,用于向段落添加文本区域。
类方法 (Class Methods)
Sr.No. | 方法和描述 |
---|---|
1 | addBreak() 指定将中断放置在运行内容中的当前位置。 |
2 | addTab() 指定选项卡应放置在运行内容中的当前位置。 |
3 | setColor(java.lang.String rgbStr) 设置文本颜色。 |
4 | setFontSize(int size) 指定显示时应在此运行内容中应用于所有非复杂脚本字符的字体大小。 |
5 | setText(java.lang.String value) 设置此文本运行的文本。 |
6 | setBold(boolean value) 指定在文档中显示时,bold属性是否应应用于此运行内容中的所有非复杂脚本字符。 |
对于此类的其余方法,请参阅完整的API文档 -
XWPFStyle
这是org.apache.poi.xwpf.usermodel包下的一个类,用于向word文档中的对象元素添加不同的样式。
类方法 (Class Methods)
Sr.No. | 方法和描述 |
---|---|
1 | getNextStyleID() 它用于获取下一个样式的StyleID。 |
2 | getStyleId() 它用于获取样式的StyleID。 |
3 | getStyles() 它用于获取样式。 |
4 | setStyleId(java.lang.String styleId) 它用于设置styleID。 |
对于此类的其余方法,请参阅完整的API文档 -
XWPFTable
这是org.apache.poi.xwpf.usermodel包下的一个类,用于将表数据添加到word文档中。
类方法 (Class Methods)
Sr.No. | 方法和描述 |
---|---|
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文档中提取简单文本。
类方法 (Class Methods)
Sr.No. | 方法和描述 |
---|---|
1 | getText() 从文档中检索所有文本。 |
有关此类的其余方法,请参阅完整的API文档: POI API文档
Apache POI Word - Document
这里术语“文档”指的是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的空白Excel文件,并在命令提示符中显示以下输出 -
createdocument.docx written successfully
Apache POI Word - Paragraph
在本章中,您将学习如何创建段落以及如何使用Java将其添加到文档中。 段落是Word文件中页面的一部分。
完成本章后,您将能够创建段落并对其执行读取操作。
创建一个段落
首先,让我们使用前面章节中讨论的引用类创建一个Paragraph。 按照上一章,首先创建一个Document,然后我们可以创建一个Paragraph。
以下代码段用于创建电子表格 -
//Create Blank document
XWPFDocument document = new XWPFDocument();
//Create a blank spreadsheet
XWPFParagraph paragraph = document.createParagraph();
在Paragraph上运行
您可以使用Run输入文本或任何对象元素。 使用Paragraph实例可以创建run 。
以下代码段用于创建运行。
XWPFRun run = paragraph.createRun();
写入段落
让我们尝试在文档中输入一些文本。 考虑以下文本数据 -
At iowiki.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 iowiki.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文件如下所示。
Apache POI Word - Borders
在本章中,您将学习如何使用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 iowiki.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,的文件中ApplyingBorder.java,从命令提示符编译并执行它,如下所示 -
$javac ApplyingBorder.java
$java ApplyingBorder
如果您的系统配置了POI库,那么它将编译并执行以在您当前目录中生成名为applyingborder.docx的Word文档并显示以下输出 -
applyingborder.docx written successfully
applyingborder.docx文件如下所示 -
Apache POI Word - Tables
在本章中,您将学习如何在文档中创建数据表。 您可以使用XWPFTable类创建表数据。 通过将每个Row添加到表并将每个cell添加到Row,您将获得表数据。
Create Table
以下代码用于在文档中创建表 -
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.的文件中CreateTable.java. 从命令提示符编译并执行它,如下所示 -
$javac CreateTable.java
$java CreateTable
它在当前目录中生成名为createtable.docx的Word文件,并在命令提示符下显示以下输出 -
createtable.docx written successfully
createtable.docx文件如下所示 -
Apache POI Word - Font & Alignment
本章介绍如何使用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文件如下所示。
对齐(Alignment)
以下代码用于设置段落文本的对齐方式 -
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 iowiki.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 IOWIKI (I) Pvt. Ltd. He came up with the " +
"website iowiki.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文件如下所示 -
Apache POI Word - Text Extraction
本章介绍如何使用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. 从命令提示符编译并执行它,如下所示 -
$javac WordExtractor.java
$java WordExtractor
它将生成以下输出:
At iowiki.com, we strive hard to provide quality tutorials for self-learning
purpose in the domains of Academics, Information Technology, Management and Computer
Programming Languages.