目錄
?
?前言
????????Apache POI是一個強大的Java庫,廣泛用于處理Microsoft Office文檔,包括Word、Excel和PowerPoint等。本文將詳細介紹如何使用Apache POI庫操作Word模板(包括替換占位符、操作表格)、將Word文檔轉換為PDF,以及如何處理PowerPoint文檔。我們將通過代碼示例逐步演示這些操作。
1. Apache POI簡介
依賴配置
2. 操作Word模板中的占位符
示例:替換占位符
3. 操作Word模板中的表格
示例:操作表格
4. 將Word文檔轉換為PDF
示例:使用Apache PDFBox將Word轉換為PDF
5. 處理PowerPoint文檔
示例:操作PowerPoint文檔
6. 總結
?前言
????????Apache POI是一個強大的Java庫,廣泛用于處理Microsoft Office文檔,包括Word、Excel和PowerPoint等。本文將詳細介紹如何使用Apache POI庫操作Word模板(包括替換占位符、操作表格)、將Word文檔轉換為PDF,以及如何處理PowerPoint文檔。我們將通過代碼示例逐步演示這些操作。
1. Apache POI簡介
Apache POI(Poor Obfuscation Implementation)是一個開源的Java庫,主要用于處理Microsoft Office文檔。它支持多種Office文檔格式,包括:
- Word:
.doc
(舊版)和.docx
(新版)。 - Excel:
.xls
(舊版)和.xlsx
(新版)。 - PowerPoint:
.ppt
(舊版)和.pptx
(新版)。
依賴配置
在使用Apache POI之前,需要在項目中添加相關的依賴。以下是Maven項目中常用的依賴配置:
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.17</version>
</dependency>
- poi:包含POI的核心功能,支持舊版Office格式。
- poi-ooxml:支持新版Office格式(如
.docx
、.xlsx
、.pptx
)。 - poi-scratchpad:提供了一些額外的功能,如處理Outlook郵件格式。
2. 操作Word模板中的占位符
在Word模板中,我們通常使用${}
作為占位符,表示需要動態替換的內容。以下代碼示例展示了如何讀取Word模板并替換占位符。
示例:替換占位符
假設我們有一個Word模板template.docx
,內容如下:
尊敬的${name}:您的訂單編號為${orderId},已成功支付。
簡單代碼示例:
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordTemplateExample {public static void main(String[] args) throws IOException {// 打開Word模板FileInputStream file = new FileInputStream("template.docx");XWPFDocument document = new XWPFDocument(file);// 定義占位符的替換內容Map<String, String> replacements = new HashMap<>();replacements.put("${name}", "張三");replacements.put("${orderId}", "123456");// 遍歷段落并替換占位符for (XWPFParagraph paragraph : document.getParagraphs()) {String text = paragraph.getText();for (Map.Entry<String, String> entry : replacements.entrySet()) {if (text != null && text.contains(entry.getKey())) {text = text.replace(entry.getKey(), entry.getValue());paragraph.removeRun(0); // 刪除原有內容paragraph.createRun().setText(text); // 插入新內容}}}// 保存修改后的文檔FileOutputStream out = new FileOutputStream("output.docx");document.write(out);// 關閉文檔document.close();out.close();}
}
3. 操作Word模板中的表格
Word文檔中的表格是常見的結構化數據展示方式。以下代碼示例展示了如何讀取和修改Word模板中的表格。
示例:操作表格
假設我們有一個Word模板template.docx
,其中包含一個表格:
| 姓名 | 年齡 | 性別 |
|--------|------|------|
| ${name}| ${age}| ${gender}|
?簡單代碼示例:
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordTableExample {public static void main(String[] args) throws IOException {// 打開Word模板FileInputStream file = new FileInputStream("template.docx");XWPFDocument document = new XWPFDocument(file);// 定義占位符的替換內容Map<String, String> replacements = new HashMap<>();replacements.put("${name}", "李四");replacements.put("${age}", "25");replacements.put("${gender}", "男");// 遍歷表格并替換占位符for (XWPFTable table : document.getTables()) {for (XWPFTableRow row : table.getRows()) {for (XWPFTableCell cell : row.getTableCells()) {for (XWPFParagraph paragraph : cell.getParagraphs()) {String text = paragraph.getText();for (Map.Entry<String, String> entry : replacements.entrySet()) {if (text != null && text.contains(entry.getKey())) {text = text.replace(entry.getKey(), entry.getValue());paragraph.removeRun(0); // 刪除原有內容paragraph.createRun().setText(text); // 插入新內容}}}}}}// 保存修改后的文檔FileOutputStream out = new FileOutputStream("output.docx");document.write(out);// 關閉文檔document.close();out.close();}
}
4. 將Word文檔轉換為PDF
將Word文檔轉換為PDF是一個常見的需求。我們可以使用Apache POI結合其他庫(如Apache PDFBox
或iText
)來實現這一功能。
示例:使用Apache PDFBox將Word轉換為PDF
首先,添加PDFBox的依賴:
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.27</version>
</dependency>
簡單代碼示例:
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WordToPdfExample {public static void main(String[] args) throws IOException {// 打開Word文檔FileInputStream file = new FileInputStream("output.docx");XWPFDocument document = new XWPFDocument(file);// 創建PDF文檔PDDocument pdfDocument = new PDDocument();PDPage page = new PDPage();pdfDocument.addPage(page);// 寫入PDF內容PDPageContentStream contentStream = new PDPageContentStream(pdfDocument, page);contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);contentStream.beginText();contentStream.newLineAtOffset(100, 700);for (XWPFParagraph paragraph : document.getParagraphs()) {contentStream.showText(paragraph.getText());contentStream.newLineAtOffset(0, -15);}contentStream.endText();contentStream.close();// 保存PDF文件pdfDocument.save("output.pdf");// 關閉文檔pdfDocument.close();document.close();}
}
5. 處理PowerPoint文檔
Apache POI也支持處理PowerPoint文檔。以下代碼示例展示了如何讀取和修改PowerPoint文檔。
示例:操作PowerPoint文檔
假設我們有一個PowerPoint模板template.pptx
,其中包含一個幻燈片,內容為:
標題:${title}
內容:${content}
操作PowerPoint文檔的簡單代碼示例:
import org.apache.poi.xslf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PowerPointExample {public static void main(String[] args) throws IOException {// 打開PowerPoint模板FileInputStream file = new FileInputStream("template.pptx");XMLSlideShow ppt = new XMLSlideShow(file);// 定義占位符的替換內容Map<String, String> replacements = new HashMap<>();replacements.put("${title}", "項目報告");replacements.put("${content}", "這是項目的最新進展。");// 遍歷幻燈片并替換占位符for (XSLFSlide slide : ppt.getSlides()) {for (XSLFShape shape : slide.getShapes()) {if (shape instanceof XSLFTextShape) {XSLFTextShape textShape = (XSLFTextShape) shape;String text = textShape.getText();for (Map.Entry<String, String> entry : replacements.entrySet()) {if (text != null && text.contains(entry.getKey())) {text = text.replace(entry.getKey(), entry.getValue());textShape.clearText(); // 清除原有內容textShape.setText(text); // 插入新內容}}}}}// 保存修改后的文檔FileOutputStream out = new FileOutputStream("output.pptx");ppt.write(out);// 關閉文檔ppt.close();out.close();}
}
6. 總結
通過Apache POI庫,可以輕松地操作Word模板(包括替換占位符、操作表格)、將Word文檔轉換為PDF,以及處理PowerPoint文檔。本文提供了詳細的代碼示例,幫助您快速上手這些操作。如果您有更多需求或問題,歡迎在評論區留言討論!