Java利用Apache POI實現(xiàn)多模板Word文檔生成的示例代碼
更新時間:2025年07月14日 08:45:53 作者:自由的瘋
當 Word 模板文檔的內容是復雜表單時,處理方式會比普通文字更復雜一些,但依舊可以借助 Apache POI 庫來完成,以下是詳細的處理思路和示例代碼,需要的朋友可以參考下
處理思路
- 識別表單元素:復雜表單里可能包含表格、文本框、下拉框等元素。你需要對這些元素進行識別,并且明確要替換內容的位置。
- 替換表格內容:對于表格,要定位到具體的單元格,然后對單元格內的內容進行替換。
- 處理文本框:文本框也是需要特別處理的元素,要遍歷文檔中的文本框并替換其中的內容。
- 動態(tài)賦值:和處理普通文字一樣,利用占位符來進行動態(tài)賦值。
示例代碼
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class ComplexFormDocGenerator {
public static void main(String[] args) {
String[] templatePaths = {"complex_template.docx"};
String outputPath = "complex_output.docx";
Map<String, String> values = new HashMap<>();
values.put("${name}", "李四");
values.put("${department}", "技術部");
try {
generateDocument(templatePaths, outputPath, values);
System.out.println("文檔生成成功,路徑為: " + outputPath);
} catch (IOException e) {
System.err.println("生成文檔時出現(xiàn)錯誤: " + e.getMessage());
e.printStackTrace();
}
}
public static void generateDocument(String[] templatePaths, String outputPath, Map<String, String> values) throws IOException {
XWPFDocument finalDocument = new XWPFDocument();
for (String templatePath : templatePaths) {
try (FileInputStream templateStream = new FileInputStream(templatePath);
XWPFDocument templateDocument = new XWPFDocument(templateStream)) {
replacePlaceholders(templateDocument, values);
appendDocument(finalDocument, templateDocument);
}
}
try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {
finalDocument.write(outputStream);
}
}
private static void replacePlaceholders(XWPFDocument document, Map<String, String> values) {
// 處理段落中的占位符
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : values.entrySet()) {
text = text.replace(entry.getKey(), entry.getValue());
}
run.setText(text, 0);
}
}
}
// 處理表格中的占位符
for (XWPFTable table : document.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : values.entrySet()) {
text = text.replace(entry.getKey(), entry.getValue());
}
run.setText(text, 0);
}
}
}
}
}
}
// 處理文本框中的占位符(POI 對文本框處理有限,可結合其他庫)
// 這里僅簡單示例,實際可能需要更復雜邏輯
// 可以使用 docx4j 等庫來更好地處理文本框
for (IBodyElement element : document.getBodyElements()) {
if (element instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT) element;
for (XWPFParagraph paragraph : sdt.getContent().getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : values.entrySet()) {
text = text.replace(entry.getKey(), entry.getValue());
}
run.setText(text, 0);
}
}
}
}
}
}
private static void appendDocument(XWPFDocument mainDocument, XWPFDocument appendDocument) throws IOException {
CTBody mainBody = mainDocument.getDocument().getBody();
CTBody appendBody = appendDocument.getDocument().getBody();
for (Object object : appendBody.getContent()) {
mainBody.addNewP().set(object);
}
}
}
代碼解釋
- ?
?main?? 方法:和處理普通文字的示例類似,定義了模板文件路徑、輸出文件路徑以及動態(tài)賦值的內容,然后調用 ??generateDocument?? 方法生成文檔。 - ?
?generateDocument?? 方法:循環(huán)讀取每個模板文件,對其進行動態(tài)賦值,再將內容追加到最終文檔里,最后把最終文檔寫入輸出文件。 - ?
?replacePlaceholders?? 方法:
- 處理段落:和普通文字處理一樣,遍歷文檔中的段落和運行對象,把占位符替換成實際的值。
- 處理表格:遍歷文檔中的所有表格,再遍歷表格的行和單元格,對單元格內的段落和運行對象進行占位符替換。
- 處理文本框:使用 ?
?XWPFSDT??? 來識別文本框,遍歷文本框內的段落和運行對象,進行占位符替換。不過 Apache POI 對文本框的處理能力有限,實際應用中可能需要結合 ??docx4j?? 等其他庫。
- ?
?appendDocument?? 方法:將一個文檔的內容追加到另一個文檔中。
注意事項
- 要保證 ?
?complex_template.docx?? 文件存在于項目的根目錄下,或者根據(jù)實際情況修改文件路徑。 - 運行代碼前,要確保項目中已經(jīng)正確引入了 Apache POI 的依賴。
- 對于復雜的表單元素,如下拉框、復選框等,可能需要更復雜的處理邏輯,你可以結合 ?
?docx4j?? 等庫來實現(xiàn)。
到此這篇關于Java利用Apache POI實現(xiàn)多模板Word文檔生成的示例代碼的文章就介紹到這了,更多相關Java Apache POI多模板Word生成內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot整合Nacos組件環(huán)境搭建和入門案例詳解(最新推薦)
本文介紹了Nacos的基礎概念、關鍵特性、專業(yè)術語和生態(tài)圈,如何在Windows環(huán)境下搭建Nacos單個服務,以及如何整合SpringBoot2來使用Nacos進行服務注冊和配置管理,感興趣的朋友一起看看吧2025-03-03

