如何用Apache POI在Java中给Word文档指定位置附加Excel工作簿?
使用Apache POI在Word指定位置嵌入Excel工作簿(Java实现)
完全可以通过Apache POI实现这个需求,核心是利用POI对Word中OLE嵌入对象的支持——Excel工作簿属于OLE对象的一种,我们可以将Excel文件以二进制形式嵌入到Word的指定位置。
实现步骤与代码示例
首先确保你的项目引入了Apache POI的必要依赖(推荐使用5.x版本),然后参考以下代码:
import org.apache.poi.xwpf.usermodel.*; import org.apache.poi.util.IOUtils; import java.io.*; public class WordEmbedExcel { public static void main(String[] args) throws IOException { // 读取现有Word文档 try (FileInputStream wordIn = new FileInputStream("existing_document.docx"); XWPFDocument doc = new XWPFDocument(wordIn); FileInputStream excelIn = new FileInputStream("embedded_workbook.xlsx")) { // 将Excel文件转为二进制数组 byte[] excelBytes = IOUtils.toByteArray(excelIn); // 定位插入位置:示例通过书签名查找,也可改用段落索引/文本匹配 String targetBookmark = "insert_excel_here"; XWPFParagraph targetPara = null; for (XWPFParagraph para : doc.getParagraphs()) { for (XWPFRun run : para.getRuns()) { if (run.getCTR().getBookmarkStartList().stream() .anyMatch(bm -> bm.getName().equals(targetBookmark))) { targetPara = para; break; } } if (targetPara != null) break; } if (targetPara == null) { System.err.println("未找到指定的插入位置"); return; } // 创建OLE对象配置 XWPFRun embedRun = targetPara.createRun(); // Excel工作簿的CLSID和ProgId,对应xlsx格式 String excelCLSID = "00020812-0000-0000-C000-000000000046"; embedRun.getCTR().addNewObject().addNewOleObject() .setClsid(excelCLSID) .setType("Embed") .setProgId("Excel.Sheet.12") .setShapeId(1); // 将Excel二进制数据写入OLE包 XWPFPackagePart olePart = doc.createRelationship( "application/vnd.openxmlformats-officedocument.oleObject", XWPFRelation.OLE_OBJECT, doc.getPackagePart(), null ); try (OutputStream oleOut = olePart.getOutputStream()) { oleOut.write(excelBytes); } // 保存修改后的文档 try (FileOutputStream wordOut = new FileOutputStream("word_with_embedded_excel.docx")) { doc.write(wordOut); } } } }
关键说明
- 定位插入位置:示例使用书签定位,你也可以通过段落索引(
doc.getParagraphs().get(索引值))或查找特定文本的方式确定插入点。 - OLE参数适配:
- 若嵌入xls格式文件,将
ProgId改为Excel.Sheet.8,CLSID保持不变。 ShapeId可自定义,确保在文档中唯一即可。
- 若嵌入xls格式文件,将
- 依赖注意:需引入
poi、poi-ooxml、poi-ooxml-full相关依赖,版本保持一致避免兼容性问题。
内容的提问来源于stack exchange,提问作者pranavs
相关产品推荐
相关产品推荐

