首页 > 网站 > WEB开发 > 正文

java 使用 POI替换doc中的文字

2024-04-27 15:03:35
字体:
来源:转载
供稿:网友

在web开发中经常碰到需要导出文档的场景,一般是在Word模板的基础上添加一些系统数据即可,用POI的range可以方便的实现这一需求。 然而,使用getRange方法有可能破坏word文档中插入的图片。解决办法是把文档中图片版式改为嵌入型

package com.poi.test;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.HashMap;import java.util.Map;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.usermodel.Range;import org.apache.poi.poifs.filesystem.POIFSFileSystem;public class PoiTest { public static void docReplaceWithPOI(String sourcePath, String targetPath, Map<String, String> map) { HWPFDocument doc = null; try { InputStream inp = new FileInputStream(sourcePath); POIFSFileSystem fs = new POIFSFileSystem(inp); doc = new HWPFDocument(fs); Range range = doc.getRange(); for (Map.Entry<String, String> entry : map.entrySet()) { range.replaceText(entry.getKey(), entry.getValue()); } inp.close(); OutputStream os = new FileOutputStream(targetPath); doc.write(os); } catch (IOException e) { e.PRintStackTrace(); } } public static void main(String[] args) { String sourcePath = "C://model.doc"; String targetPath = "C://output.doc"; Map<String,String> map = new HashMap<String, String>(); map.put("#姓名#", "张三"); map.put("#年龄#", "20"); docReplaceWithPOI(sourcePath,targetPath,map); }}

POI版本是3.9或更高 maven 配置:

<dependency> <groupId>tac.lib</groupId> <artifactId>poi</artifactId> <version>3.9</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>tac.lib</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.9</version> <type>jar</type> <scope>compile</scope> </dependency>
上一篇:5.列偏移

下一篇:web.xml的配置详解

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表