如何用Java操作Word?Apache POI教程

apache poi 是 Java 操作 word 文檔的常用工具,支持 .doc 和 .docx 格式。1. 讀取內(nèi)容:對(duì) .doc 使用 hwpfdocument,對(duì) .docx 使用 xwpfdocument 遍歷段落獲取文本。2. 寫入內(nèi)容:通過 xwpfdocument 創(chuàng)建段落和運(yùn)行實(shí)例,設(shè)置文本并保存文件,可設(shè)置字體樣式。3. 替換模板變量:遍歷段落和運(yùn)行實(shí)例,查找并替換占位符如 ${name}。4. 插入表格和圖片:使用 xwpftable 添加表格內(nèi)容,通過 addpicturedata 和 addpicture 插入圖片,單位需轉(zhuǎn)換為 emu。注意資源釋放、版本差異及復(fù)雜結(jié)構(gòu)處理。

如何用Java操作Word?Apache POI教程

用Java操作Word文檔,最常用的工具之一就是 apache POI。它支持讀寫 microsoft office 格式文件,包括 Word(.doc 和 .docx)。雖然處理 Word 的功能不如 excel 強(qiáng)大,但日常需求基本都能滿足。

如何用Java操作Word?Apache POI教程

下面介紹幾個(gè)常見的使用場(chǎng)景和操作方法,適合剛上手的開發(fā)者。

如何用Java操作Word?Apache POI教程


讀取 Word 文檔內(nèi)容

如果你只是想從一個(gè) .doc 或 .docx 文件中提取文字內(nèi)容,POI 提供了比較直接的方式。

立即學(xué)習(xí)Java免費(fèi)學(xué)習(xí)筆記(深入)”;

對(duì)于 .doc 文件(Office 2003 及以前):

如何用Java操作Word?Apache POI教程

FileInputStream fis = new FileInputStream("test.doc"); HWPFDocument doc = new HWPFDocument(fis); String text = doc.getDocumentText(); System.out.println(text);

對(duì)于 .docx 文件(Office 2007+):

XWPFDocument document = new XWPFDocument(new FileInputStream("test.docx")); for (XWPFParagraph paragraph : document.getParagraphs()) {     System.out.println(paragraph.getText()); }

注意:如果文檔結(jié)構(gòu)復(fù)雜,比如包含表格、圖片等,就需要遍歷段落的同時(shí)判斷不同元素類型來分別處理。


向 Word 中寫入內(nèi)容

創(chuàng)建一個(gè)新的 Word 文檔并寫入文本也很簡單。

生成 .docx 文件示例:

XWPFDocument document = new XWPFDocument();  // 添加一段文字 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("這是一個(gè)新文檔的內(nèi)容");  // 保存到文件 try (FileOutputStream out = new FileOutputStream("output.docx")) {     document.write(out); }

你還可以設(shè)置字體、加粗、顏色等格式,只需要在 XWPFRun 上調(diào)用相應(yīng)方法即可。

常見問題注意點(diǎn):

  • 不同版本 POI 的 API 可能略有差異,建議查看對(duì)應(yīng)版本文檔。
  • 寫入后務(wù)必關(guān)閉流或 try-with-resources,避免資源泄露。
  • 如果要覆蓋已有文檔內(nèi)容,需要先加載再修改。

替換 Word 模板中的占位符

實(shí)際開發(fā)中,經(jīng)常使用 Word 模板替換變量,比如“${name}”替換成具體值。

實(shí)現(xiàn)思路是遍歷所有段落和表格單元格,查找特定標(biāo)記并替換:

for (XWPFParagraph para : document.getParagraphs()) {     for (XWPFRun run : para.getRuns()) {         String text = run.getText(0);         if (text != null && text.contains("${name}")) {             text = text.replace("${name}", "張三");             run.setText(text, 0);         }     } }

這種方式適用于簡單的變量替換。如果是復(fù)雜的模板填充,可能還需要結(jié)合表格、列表甚至圖片插入。


插入表格和圖片

除了純文本,POI 也支持插入表格和圖片。

插入表格:

XWPFTable table = document.createTable(2, 2); table.getRow(0).getCell(0).setText("第一行第一列"); table.getRow(0).getCell(1).setText("第一行第二列");

插入圖片:

FileInputStream imageStream = new FileInputStream("logo.png"); int format = XWPFDocument.PICTURE_TYPE_PNG; String blipId = document.addPicturedata(imageStream, format); XWPFRun run = paragraph.createRun(); run.addPicture(blipId, format, "logo.png", Units.toEMU(200), Units.toEMU(100));

注意:插入圖片時(shí)單位要用 EMU(English Metric Unit),Apache POI 提供了 Units 工具類轉(zhuǎn)換像素。


? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊11 分享