本文目录导读:

我来为您提供Apache POI操作Word文档的完整案例,涵盖创建、读取和修改Word文档。
Maven依赖配置
<dependencies>
<!-- Apache POI 核心 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<!-- Apache POI OOXML (处理.docx格式) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<!-- 日志依赖 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
</dependencies>
创建Word文档
1 创建简单文档
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.model.XWPFHyperlinkRun;
import org.apache.poi.wp.usermodel.HyperlinkType;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
public class CreateWordDocument {
public static void createSimpleDocument(String filePath) throws IOException {
try (XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(filePath)) {
// 创建标题段落
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setText("这是一个简单的Word文档");
titleRun.setBold(true);
titleRun.setFontSize(20);
titleRun.setColor("2E74B5");
// 创建正文段落
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("这是正文内容,演示如何使用Apache POI创建Word文档。");
run.setFontSize(12);
// 添加第二段
XWPFParagraph paragraph2 = document.createParagraph();
XWPFRun run2 = paragraph2.createRun();
run2.setText("Apache POI 是一个开源的Java库,用于读写Microsoft Office格式的文件。");
run2.setItalic(true);
// 设置页面边距
document.getDocument().setBody();
document.write(out);
}
}
}
2 创建带样式的文档
public class CreateFormattedDocument {
public static void createFormattedDoc(String filePath) throws IOException {
try (XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(filePath)) {
// 1. 创建带样式的段落
XWPFParagraph styledParagraph = document.createParagraph();
styledParagraph.setAlignment(ParagraphAlignment.LEFT);
styledParagraph.setIndentationLeft(300);
styledParagraph.setSpacingAfter(200);
styledParagraph.setSpacingBefore(200);
XWPFRun run1 = styledParagraph.createRun();
run1.setText("这是一个带样式的段落");
run1.setBold(true);
run1.setFontSize(14);
run1.setColor("FF0000");
run1.setFontFamily("Arial");
// 2. 创建项目符号列表
XWPFParagraph bulletParagraph = document.createParagraph();
bulletParagraph.setIndentationLeft(400);
XWPFRun bulletRun = bulletParagraph.createRun();
bulletRun.setText("• 这是项目符号1");
XWPFParagraph bulletParagraph2 = document.createParagraph();
bulletParagraph2.setIndentationLeft(400);
XWPFRun bulletRun2 = bulletParagraph2.createRun();
bulletRun2.setText("• 这是项目符号2");
// 3. 创建编号列表
XWPFNumbering numbering = document.createNumbering();
// 4. 创建表格
XWPFTable table = document.createTable(3, 3);
table.setWidth("100%");
// 设置表格内容
String[][] data = {
{"姓名", "年龄", "城市"},
{"张三", "25", "北京"},
{"李四", "30", "上海"}
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
XWPFTableCell cell = table.getRow(i).getCell(j);
cell.setText(data[i][j]);
}
}
document.write(out);
}
}
}
读取Word文档
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
public class ReadWordDocument {
public static void readDocument(String filePath) throws IOException {
try (FileInputStream fis = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(fis)) {
// 读取段落内容
System.out.println("=== 文档段落内容 ===");
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (int i = 0; i < paragraphs.size(); i++) {
XWPFParagraph paragraph = paragraphs.get(i);
System.out.println("段落 " + (i + 1) + ": " + paragraph.getText());
// 获取段落样式
System.out.println(" 样式: " + paragraph.getStyle());
System.out.println(" 对齐方式: " + paragraph.getAlignment());
// 读取段落中的run
for (XWPFRun run : paragraph.getRuns()) {
System.out.println(" Run内容: " + run.text());
System.out.println(" 是否加粗: " + run.isBold());
System.out.println(" 字体大小: " + run.getFontSize());
System.out.println(" 字体: " + run.getFontFamily());
}
}
// 读取表格内容
System.out.println("\n=== 文档表格内容 ===");
List<XWPFTable> tables = document.getTables();
for (int i = 0; i < tables.size(); i++) {
System.out.println("表格 " + (i + 1) + ":");
XWPFTable table = tables.get(i);
for (int j = 0; j < table.getNumberOfRows(); j++) {
XWPFTableRow row = table.getRow(j);
String rowContent = "";
for (int k = 0; k < row.getTableCells().size(); k++) {
rowContent += row.getCell(k).getText() + " | ";
}
System.out.println(" 行 " + (j + 1) + ": " + rowContent);
}
}
// 读取文档属性
System.out.println("\n=== 文档属性 ===");
System.out.println("作者: " + document.getProperties().getCoreProperties().getCreator());
System.out.println("标题: " + document.getProperties().getCoreProperties().getTitle());
System.out.println("修改时间: " + document.getProperties().getCoreProperties().getModified());
}
}
}
修改Word文档
public class ModifyWordDocument {
public static void modifyDocument(String filePath) throws IOException {
try (FileInputStream fis = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(fis);
FileOutputStream out = new FileOutputStream(filePath)) {
// 1. 修改段落内容
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
// 查找特定内容并替换
if (text.contains("旧文本")) {
replaceTextInParagraph(paragraph, "旧文本", "新文本");
}
}
// 2. 添加新段落
XWPFParagraph newParagraph = document.createParagraph();
XWPFRun newRun = newParagraph.createRun();
newRun.setText("这是添加的新段落");
newRun.setBold(true);
// 3. 删除指定段落
// 找到要删除的段落索引
XWPFParagraph deleteParagraph = null;
for (XWPFParagraph paragraph : paragraphs) {
if (paragraph.getText().contains("要删除的内容")) {
deleteParagraph = paragraph;
break;
}
}
if (deleteParagraph != null) {
document.removeBodyElement(document.getPosOfParagraph(deleteParagraph));
}
// 4. 修改表格内容
List<XWPFTable> tables = document.getTables();
if (!tables.isEmpty()) {
XWPFTable table = tables.get(0);
if (table.getNumberOfRows() > 0) {
XWPFTableRow row = table.getRow(0);
XWPFTableCell cell = row.getCell(0);
cell.setText("修改后的内容");
}
}
// 5. 设置单元格背景色
if (!tables.isEmpty()) {
XWPFTable table = tables.get(0);
if (table.getNumberOfRows() > 1) {
XWPFTableRow row = table.getRow(1);
XWPFTableCell cell = row.getCell(0);
cell.setColor("FFEB3B"); // 黄色背景
}
}
document.write(out);
}
}
private static void replaceTextInParagraph(XWPFParagraph paragraph, String searchText, String replaceText) {
List<XWPFRun> runs = paragraph.getRuns();
if (runs.isEmpty()) return;
String paragraphText = paragraph.getText();
if (paragraphText.contains(searchText)) {
// 简化处理:清除所有runs,然后重新创建
for (XWPFRun run : runs) {
run.setText("", 0);
}
runs.get(0).setText(paragraphText.replace(searchText, replaceText));
}
}
}
高级功能示例
1 插入图片
public class InsertImageToWord {
public static void insertImage(String filePath, String imagePath) throws IOException {
try (XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(filePath)) {
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
// 插入图片
try (FileInputStream imageStream = new FileInputStream(imagePath)) {
int imageType = Document.PICTURE_TYPE_JPEG; // 根据图片类型调整
run.addPicture(imageStream, imageType, "image.jpg",
Units.toEMU(200), // 宽度200px
Units.toEMU(200)); // 高度200px
} catch (Exception e) {
e.printStackTrace();
}
document.write(out);
}
}
}
2 创建带有超链接的文档
import org.apache.poi.xwpf.usermodel.XWPFHyperlink;
import org.apache.poi.common.usermodel.HyperlinkType;
public class CreateHyperlinkDocument {
public static void createDocWithLink(String filePath) throws IOException {
try (XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(filePath)) {
XWPFParagraph paragraph = document.createParagraph();
// 创建超链接
XWPFParagraph linkParagraph = document.createParagraph();
XWPFRun run = linkParagraph.createRun();
run.setText("访问OpenAI网站: ");
XWPFHyperlink hyperlink = createHyperlink(linkParagraph, "https://www.openai.com", "OpenAI");
document.write(out);
}
}
private static XWPFHyperlink createHyperlink(XWPFParagraph paragraph, String url, String text) {
XWPFHyperlinkRun linkRun = new XWPFHyperlinkRun(null, null, null, null);
linkRun.setText(text);
// 设置超链接地址
XWPFHyperlink hyperlink = new XWPFHyperlink(url);
paragraph.addRun(linkRun);
return hyperlink;
}
}
3 文档加密
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.standard.StandardEncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class EncryptWordDocument {
public static void encryptDocument(String filePath, String password) throws IOException {
try (XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(filePath)) {
// 添加一些内容
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("这是一个加密的文档");
// 加密文档
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
StandardEncryptionInfo encInfo = (StandardEncryptionInfo) info;
encInfo.setPassword(password);
// 写入加密后的文件
document.write(out);
}
}
}
完整示例:生成报告
public class GenerateReport {
public static void generateReport(String filePath) throws IOException {
try (XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(filePath)) {
// 创建报告标题
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setText("月度销售报告");
titleRun.setBold(true);
titleRun.setFontSize(24);
titleRun.setColor("2E74B5");
// 创建日期信息
XWPFParagraph datePara = document.createParagraph();
datePara.setAlignment(ParagraphAlignment.CENTER);
XWPFRun dateRun = datePara.createRun();
dateRun.setText("2024年1月");
dateRun.setFontSize(12);
// 创建摘要部分
XWPFParagraph summaryTitle = document.createParagraph();
XWPFRun summaryTitleRun = summaryTitle.createRun();
summaryTitleRun.setText("quot;);
summaryTitleRun.setBold(true);
summaryTitleRun.setFontSize(16);
XWPFParagraph summary = document.createParagraph();
summary.setSpacingAfter(200);
XWPFRun summaryRun = summary.createRun();
summaryRun.setText("本报告总结了2024年1月的销售情况,总销售额为1,000,000元,较上月增长15%。");
summaryRun.setFontSize(12);
// 创建销售数据表
XWPFTable table = document.createTable(4, 4);
table.setWidth("100%");
String[][] data = {
{"产品", "销售额", "增长", "占比"},
{"产品A", "500,000", "+20%", "50%"},
{"产品B", "300,000", "+10%", "30%"},
{"产品C", "200,000", "+15%", "20%"}
};
// 填充表格
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
XWPFTableCell cell = table.getRow(i).getCell(j);
cell.setText(data[i][j]);
// 设置表头样式
if (i == 0) {
cell.setColor("D9E2F3"); // 浅蓝色背景
}
}
}
// 创建结论部分
XWPFParagraph conclusionTitle = document.createParagraph();
XWPFRun conclusionTitleRun = conclusionTitle.createRun();
conclusionTitleRun.setText("quot;);
conclusionTitleRun.setBold(true);
conclusionTitleRun.setFontSize(16);
XWPFParagraph conclusion = document.createParagraph();
XWPFRun conclusionRun = conclusion.createRun();
conclusionRun.setText("根据本月销售数据,整体表现良好,建议继续关注产品A的增长潜力,并优化产品C的营销策略。");
conclusionRun.setFontSize(12);
// 设置文档属性
document.getProperties().getCoreProperties().setCreator("销售部门");
document.getProperties().getCoreProperties().setTitle("月度销售报告");
document.getProperties().getCoreProperties().setSubject("2024年1月销售分析");
document.write(out);
}
}
}
主程序测试
public class Main {
public static void main(String[] args) {
try {
// 1. 创建简单文档
CreateWordDocument.createSimpleDocument("simple.docx");
// 2. 创建格式化文档
CreateFormattedDocument.createFormattedDoc("formatted.docx");
// 3. 读取文档
ReadWordDocument.readDocument("simple.docx");
// 4. 修改文档
ModifyWordDocument.modifyDocument("simple.docx");
// 5. 生成报告
GenerateReport.generateReport("sales_report.docx");
System.out.println("所有文档操作完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 内存管理:处理大文档时,建议分批处理,避免内存溢出
- 版本兼容:POI 4.0+ 支持Office 2007+格式(.docx),老格式(.doc)需要特殊处理
- 性能优化:大量写入操作时,考虑使用缓冲流
- 编码问题:确保正确处理中文编码,设置合适的字体
- 资源关闭:始终使用try-with-resources确保资源正确释放
这是一个完整的Apache POI操作Word文档的案例集合,涵盖了常见的操作场景,您可以根据实际需求进行修改和扩展。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播