java 根据word模板生成word文件

合集下载

java使用POI操作XWPFDocument生成Word实战(一)

java使用POI操作XWPFDocument生成Word实战(一)

java使⽤POI操作XWPFDocument⽣成Word实战(⼀)注:我使⽤的word 2016功能简介:(1)使⽤jsoup解析html得到我⽤来⽣成word的⽂本(这个你们可以忽略)(2)⽣成word、设置页边距、设置页脚(页码),设置页码(⽂本)⼀、解析htmlDocument doc = Jsoup.parseBodyFragment(contents);Element body = doc.body();Elements es = body.getAllElements();⼆、循环Elements获取我需要的html标签boolean tag = false;for (Element e : es) {//跳过第⼀个(默认会把整个对象当做第⼀个)if(!tag) {tag = true;continue;}//创建段落:⽣成word(核⼼)createXWPFParagraph(docxDocument,e);}三、⽣成段落/*** 构建段落* @param docxDocument* @param e*/public static void createXWPFParagraph(XWPFDocument docxDocument, Element e){XWPFParagraph paragraph = docxDocument.createParagraph();XWPFRun run = paragraph.createRun();run.setText(e.text());run.setTextPosition(35);//设置⾏间距if(e.tagName().equals("titlename")){paragraph.setAlignment(ParagraphAlignment.CENTER);//对齐⽅式run.setBold(true);//加粗run.setColor("000000");//设置颜⾊--⼗六进制run.setFontFamily("宋体");//字体run.setFontSize(24);//字体⼤⼩}else if(e.tagName().equals("h1")){addCustomHeadingStyle(docxDocument, "标题 1", 1);paragraph.setStyle("标题 1");run.setBold(true);run.setColor("000000");run.setFontFamily("宋体");run.setFontSize(20);}else if(e.tagName().equals("h2")){addCustomHeadingStyle(docxDocument, "标题 2", 2);paragraph.setStyle("标题 2");run.setBold(true);run.setColor("000000");run.setFontFamily("宋体");run.setFontSize(18);}else if(e.tagName().equals("h3")){addCustomHeadingStyle(docxDocument, "标题 3", 3);paragraph.setStyle("标题 3");run.setBold(true);run.setColor("000000");run.setFontFamily("宋体");run.setFontSize(16);}else if(e.tagName().equals("p")){//内容paragraph.setAlignment(ParagraphAlignment.BOTH);//对齐⽅式paragraph.setIndentationFirstLine(WordUtil.ONE_UNIT);//⾸⾏缩进:567==1厘⽶run.setBold(false);run.setColor("001A35");run.setFontFamily("宋体");run.setFontSize(14);//run.addCarriageReturn();//回车键}else if(e.tagName().equals("break")){paragraph.setPageBreak(true);//段前分页(ctrl+enter)}四、设置页边距/*** 设置页边距 (word中1厘⽶约等于567)* @param document* @param left* @param top* @param right* @param bottom*/public static void setDocumentMargin(XWPFDocument document, String left,String top, String right, String bottom) {CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();CTPageMar ctpagemar = sectPr.addNewPgMar();if (StringUtils.isNotBlank(left)) {ctpagemar.setLeft(new BigInteger(left));}if (StringUtils.isNotBlank(top)) {ctpagemar.setTop(new BigInteger(top));}if (StringUtils.isNotBlank(right)) {ctpagemar.setRight(new BigInteger(right));}if (StringUtils.isNotBlank(bottom)) {ctpagemar.setBottom(new BigInteger(bottom));}}五、创建页眉/*** 创建默认页眉** @param docx XWPFDocument⽂档对象* @param text 页眉⽂本* @return返回⽂档帮助类对象,可⽤于⽅法链调⽤* @throws XmlException XML异常* @throws IOException IO异常* @throws InvalidFormatException ⾮法格式异常* @throws FileNotFoundException 找不到⽂件异常*/public static void createDefaultHeader(final XWPFDocument docx, final String text){CTP ctp = CTP.Factory.newInstance();XWPFParagraph paragraph = new XWPFParagraph(ctp, docx);ctp.addNewR().addNewT().setStringValue(text);ctp.addNewR().addNewT().setSpace(SpaceAttribute.Space.PRESERVE);CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr(); XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);XWPFHeader header = policy.createHeader(STHdrFtr.DEFAULT, new XWPFParagraph[] { paragraph });header.setXWPFDocument(docx);}}六、创建页脚/*** 创建默认的页脚(该页脚主要只居中显⽰页码)** @param docx* XWPFDocument⽂档对象* @return返回⽂档帮助类对象,可⽤于⽅法链调⽤* @throws XmlException* XML异常* @throws IOException* IO异常*/public static void createDefaultFooter(final XWPFDocument docx) {// TODO 设置页码起始值CTP pageNo = CTP.Factory.newInstance();XWPFParagraph footer = new XWPFParagraph(pageNo, docx);CTPPr begin = pageNo.addNewPPr();begin.addNewPStyle().setVal(STYLE_FOOTER);begin.addNewJc().setVal(STJc.CENTER);pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);pageNo.addNewR().addNewInstrText().setStringValue("PAGE \\* MERGEFORMAT");pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);CTR end = pageNo.addNewR();CTRPr endRPr = end.addNewRPr();endRPr.addNewNoProof();endRPr.addNewLang().setVal(LANG_ZH_CN);end.addNewFldChar().setFldCharType(STFldCharType.END);CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr(); XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);policy.createFooter(STHdrFtr.DEFAULT, new XWPFParagraph[] { footer });}七、⾃定义标题样式(这个在我另⼀篇word基础中也有提及)* 增加⾃定义标题样式。

Java使用Poi-tlword模板导出word

Java使用Poi-tlword模板导出word

Java使⽤Poi-tlword模板导出word 1.导⼊依赖<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.7.3</version></dependency>2.新建⼀个word,制作导出模板模板放⼊ resource/static/word/template⽂件夹下3.编写⼯具类⼯具类--WordExportServer.javapublic class WordExportServer {/*** 导出word**/public static void export(WordExportData wordExportData) throws IOException {HttpServletResponse response=wordExportData.getResponse();OutputStream out = response.getOutputStream();;XWPFTemplate template =null;try{ClassPathResource classPathResource = new ClassPathResource(wordExportData.getTemplateDocPath());String resource = classPathResource.getURL().getPath();resource= PdfUtil1.handleFontPath(resource);//渲染表格HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();Configure config = Configure.newBuilder().bind(wordExportData.getTableDataField(), policy).build();template = pile(resource, config).render(wordExportData.getWordData());String fileName=getFileName(wordExportData);/** ===============⽣成word到设置浏览默认下载地址=============== **/// 设置强制下载不打开response.setContentType("application/force-download");// 设置⽂件名response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);template.write(out);}catch (Exception e){e.printStackTrace();}finally {out.flush();out.close();template.close();}}/*** 获取导出下载的word名称* @param wordExportData* @return ng.String**/public static String getFileName(WordExportData wordExportData){if(null !=wordExportData.getFileName()){return wordExportData.getFileName()+".docx";}return System.currentTimeMillis()+".docx";}}word数据包装类--WordExportData .java@Datapublic class WordExportData {/*** word模板路径(static/wordTemplate/dealerListDocTemplate.docx)**/private String templateDocPath;/*** word填充数据(key值与模板中的key值要保持⼀致)**/private Map<String,Object> wordData;/*** word表格数据key值**/private String tableDataField;/*** word导出后的⽂件名(不填则⽤当前时间代替)**/private String fileName;private HttpServletResponse response;}4.controller层调⽤@RequestMapping("/printWord")public void printWord(HttpServletRequest request, HttpServletResponse response) throws IOException{String[] ids=request.getParameter("ids").split(";");List<DealerDto> goodsDataList=goodsService.getDealerListByIds(ids);Map<String,Object> docData=new HashMap<>(3);docData.put("detailList",goodsDataList);docData.put("title",标题);docData.put("subTitle",副标题);WordExportData wordExportData=new WordExportData();wordExportData.setResponse(response);wordExportData.setTableDataField("detailList");wordExportData.setTemplateDocPath(DEALER_DOC_TEMPLATE_PATH);//副本存放路径wordExportData.setWordData(docData);WordExportServer.export(wordExportData);}5.前端调⽤var ids = [];for (var index in checkData) {ids.push(checkData[index].id);}var batchIds = ids.join(";");layer.confirm('确定下载选中的数据吗?', function (index) {layer.close(index);window.location.href ='/goods/printWord?ids=' + batchIds;});6.总结优点:使⽤⽅法很简单,使⽤⼯具类的⽅法,⽅便复⽤于其他模块。

java根据模板生成word文档,兼容富文本、图片

java根据模板生成word文档,兼容富文本、图片

java根据模板⽣成word⽂档,兼容富⽂本、图⽚Java⾃动⽣成带图⽚、富⽂本、表格等的word⽂档使⽤技术 freemark+jsoup ⽣成mht格式的伪word⽂档,已经应⽤项⽬中,确实是可⾏的,⽆论是富⽂本中是图⽚还是表格,都能在word中展现出来使⽤jsoup解析富⽂本框,将其中的图⽚进⾏Base64位转码,使⽤freemark替换模板的占位符,将变量以及图⽚资源放⼊模板中在输出⽂件maven地址<!--freemarker--><!--<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version></dependency><!--JavaHTMLParser--><!--<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version></dependency>制作word的freemark模板1. 先将wrod的格式内容定义好,如果需要插⼊参数的地⽅以${xxx}为表⽰,例:${product}模板例⼦: 2. 将模板另存为mht格式的⽂件,打开该⽂件检查每个变量(${product})是否完整,有可能在${}中出现其他代码,需要删除。

3. 将mht⽂件变更⽂件类型,改成ftl为结尾的⽂件,引⼊到项⽬中 4. 修改ftl模板⽂件,在⽂件中加上图⽚资源占位符${imagesBase64String},${imagesXmlHrefString}具体位置如下图所⽰: 5. ftl⽂件中由⼏个关键配置需要引⼊到代码中:docSrcParent = word.filesdocSrcLocationPrex =nextPartId = 01D2C8DD.BC13AF60上⾯三个参数,在模板⽂件中可以找到,需要进⾏配置,如果配置错误,图⽚⽂件将不会显⽰下⾯这三个参数固定,切换模板也不会改变shapeidPrex = _x56fe__x7247__x0020typeid = #_x0000_t75spidPrex = _x0000_i 6. 模板引⼊之后进⾏代码编辑源码地址为:下载源码后需要进⾏调整下内容:1. 录⼊步骤5中的6个参数2. 修改freemark获取模板⽅式下⾯这种⽅式能获取模板,但是在项⽬打包之后⽆法获取jar包内的⽂件Configuration configuration=newConfiguration(Configuration.getVersion());configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());configuration.setDirectoryForTemplateLoading(newFile(templatePath));Template template=configuration.getTemplate("xxx.ftl");通过流的形式直接创建模板对象Configuration configuration=newConfiguration(Configuration.getVersion());configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());configuration.setDirectoryForTemplateLoading(newFile(templatePath));InputStream inputStream=newFileInputStream(newFile(templatePath+"/"+templateName)); InputStreamReader inputStreamReader=newInputStreamReader(inputStream,StandardCharsets.UTF_8); Template template=newTemplate(templateName,inputStreamReader,configuration);。

java生成word的几种方案

java生成word的几种方案

java⽣成word的⼏种⽅案1、 Jacob是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建⼀座桥梁。

使⽤Jacob⾃带的DLL动态链接库,并通过JNI的⽅式实现了在Java平台上对COM程序的调⽤。

DLL动态链接库的⽣成需要windows平台的⽀持。

2、 Apache POI包括⼀系列的API,它们可以操作基于MicroSoft OLE 2 Compound Document Format的各种格式⽂件,可以通过这些API在Java中读写Excel、Word等⽂件。

他的excel处理很强⼤,对于word还局限于读取,⽬前只能实现⼀些简单⽂件的操作,不能设置样式。

3、 Java2word是⼀个在java程序中调⽤ MS Office Word ⽂档的组件(类库)。

该组件提供了⼀组简单的接⼝,以便java程序调⽤他的服务操作Word ⽂档。

这些服务包括:打开⽂档、新建⽂档、查找⽂字、替换⽂字,插⼊⽂字、插⼊图⽚、插⼊表格,在书签处插⼊⽂字、插⼊图⽚、插⼊表格等。

填充数据到表格中读取表格数据,1.1版增强的功能:指定⽂本样式,指定表格样式。

如此,则可动态排版word⽂档。

4、 iText操作Excel还⾏。

对于复杂的⼤量的word也是噩梦。

⽤法很简单, 但是功能很少, 不能设置打印⽅向等问题。

5、 JSP输出样式基本不达标,⽽且要打印出来就更是惨不忍睹。

6、⽤XML做就很简单了。

Word从2003开始⽀持XML格式,⼤致的思路是先⽤office2003或者2007编辑好word的样式,然后另存为xml,将xml翻译为FreeMarker模板,最后⽤java来解析FreeMarker模板并输出Doc。

经测试这样⽅式⽣成的word⽂档完全符合office标准,样式、内容控制⾮常便利,打印也不会变形,⽣成的⽂档和office中编辑⽂档完全⼀样。

7、补充⼀种⽅案,可以⽤类似ueditor的在线编辑器编辑word⽂档,在将html⽂件转换为xhtml⽂件,再转换为word。

几种解析Word文档的Java类库比较

几种解析Word文档的Java类库比较
受云服务的启发我想到未必非要在java中解决问题于是想到之前写过一个nodejs的项目其中涉及到office文档的生成可以利用nodejs开发一个restful的接口将所有模板放在这个项目里调用接口实现模板生成
几种解析 Word文档的 Java类库比较
推荐指数:
因为之前做过EXCEL的解析,所以我首选就是POI,然而经过调查之后发现POI解析Word文档就是个坑,非常难用不说,有些功能还不支 持。试验一番之后不得不放弃了。
推荐指数:
受云服务的启发,我想到未必非要在Java中解决问题,于是想到之前写过一个Node.js的项目,其中涉及到office文档的生成,可以利用 Node.js开发一个Restful的接口,将所有模板放在这个项目里,调用接口实现模板生成。Docxtemplater相对来讲是一个很好的Node.js office 中间件。
推荐指数:
发现POI不好用之后同事推荐给我了一种基于POI的模板类库,可以根据模板自动生成文档。语法简单,而且模板可以定制。因为这次的需 求比较特殊,所以有些地方不太满足项目的需要。如果你的项目是那种从头搭建的项目的话,建议使用这个类库。
推荐指数:
FreeMarker是一种Html模板引擎工具,因为word文档也是一种固定格式的XML文档,所以可以使用FreeMarker来设定模板,并根据模板生 成。缺点是所有doc模板都必须修改为符合标准的ftl模板文档,工程量较大。
推荐指数:
JACOB是一个Java-COM的中间件,通过这个组件你可以在Java应用程序中调用COM组件和Win32程序库。然而缺点也比较明显,就是只 能在Windows环境下使用,如果是那种需要部署到Linux环境的项目就不适用了。我没有写测试小程序,不知道具体使用起来会是怎么样。

java使用模板生成word文件

java使用模板生成word文件

java使⽤模板⽣成word⽂件springboot项⽬,模板放在了templates下⾯,后⾯要根据模板⽣成word1、⽣成⼀个word模板,如图:注:{{code}}的是需填写的参数下⾯是⽣成本地的pom⽂件<dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.jfree</groupId><artifactId>jcommon</artifactId><version>1.0.24</version></dependency><dependency><groupId>org.jfree</groupId><artifactId>jfreechart</artifactId><version>1.5.0</version></dependency>/*** @Version 1.0.0* @Description*/public class WordUtil {/*** ⽣成word* @param templatePath* @param temDir* @param fileName* @param params*/public static void exportWord(String templatePath, String temDir, String fileName, Map<String,Object> params){Assert.notNull(templatePath, "模板路径不能为空");Assert.notNull(temDir, "临时⽂件路径不能为空");Assert.notNull(fileName, "导出⽂件名不能为空");Assert.isTrue(fileName.endsWith(".docx"), "word导出请使⽤docx格式");if (!temDir.endsWith("/")) {temDir = temDir + File.separator;}File dir = new File(temDir);if (!dir.exists()) {dir.mkdirs();}try {XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);String tmpPath = temDir + fileName;FileOutputStream fos = new FileOutputStream(tmpPath);doc.write(fos);fos.flush();fos.close();} catch (Exception e) {e.printStackTrace();}}}/*** @Version 1.0.0* @Description*/public class WordDemo {public static void main(String[] args) {Map<String,Object> map = new HashMap<>();map.put("username", "张三");map.put("company","xx公司" );map.put("date","2020-04-20" );map.put("dept","IT部" );map.put("startTime","2020-04-20 08:00:00" );map.put("endTime","2020-04-20 08:00:00" );map.put("reason", "外出办公");map.put("time","2020-04-22" );WordUtil.exportWord("templates/demo.docx","D:/" ,"⽣成⽂件.docx" ,map );}}2、下⾯是下载word⽂件/*** 导出word形式* @param response*/@RequestMapping("/exportWord")public void exportWord(HttpServletResponse response){Map<String,Object> map = new HashMap<>();map.put("username", "张三");map.put("company","杭州xx公司" );map.put("date","2020-04-20" );map.put("dept","IT部" );map.put("startTime","2020-04-20 08:00:00" );map.put("endTime","2020-04-20 08:00:00" );map.put("reason", "外出办公");map.put("time","2020-04-22" );try {response.setContentType("application/msword");response.setCharacterEncoding("utf-8");String fileName = URLEncoder.encode("测试","UTF-8" );//String fileName = "测试"response.setHeader("Content-disposition","attachment;filename="+fileName+".docx" ); XWPFDocument doc = WordExportUtil.exportWord07("templates/demo.docx",map); doc.write(response.getOutputStream());} catch (Exception e) {e.printStackTrace();}//WordUtil.exportWord("templates/demo.docx","D:/" ,"⽣成⽂件.docx" ,map );} 。

JAVA生成word文档代码加说明

JAVA生成word文档代码加说明

import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Iterator;import java.util.Map;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.model.FieldsDocumentPart;import ermodel.Field;import ermodel.Fields;import ermodel.Range;import ermodel.Table;import ermodel.TableIterator;import ermodel.TableRow;publicclass WordUtil {publicstaticvoid readwriteWord(String filePath, String downPath, Map<String, String> map, int[] num, String downFileName) { //读取word模板FileInputStream in = null;try {in = new FileInputStream(new File(filePath));} catch (FileNotFoundException e1) {e1.printStackTrace();}HWPFDocument hdt = null;try {hdt = new HWPFDocument(in);} catch (IOException e1) {e1.printStackTrace();}Fields fields = hdt.getFields();Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN) .iterator();while (it.hasNext()) {System.out.println(it.next().getType());}//读取word表格内容try {Range range = hdt.getRange();//得到文档的读取范围TableIterator it2 = new TableIterator(range);//迭代文档中的表格int tabCount = 0;while (it2.hasNext()) {//System.out.println(" 第几个表格 "+tabCount);//System.out.println(num[tabCount] +" 行");Table tb2 = (Table) it2.next();//迭代行,默认从0开始for (int i = 0; i < tb2.numRows(); i++) {TableRow tr = tb2.getRow(i);// System.out.println(" fu "+num[tabCount] +" 行");if (num[tabCount] < i && i < 7) {tr.delete();}} //end fortabCount++;} //end while//替换word表格内容for (Map.Entry<String, String> entry : map.entrySet()) { range.replaceText("$"+ entry.getKey().trim() + "$", entry.getValue());}// System.out.println("替换后------------:"+range.text().trim());} catch (Exception e) {e.printStackTrace();}//System.out.println("--------------------------------------------------------------------------------------");ByteArrayOutputStream ostream = new ByteArrayOutputStream();String fileName = downFileName;fileName += ".doc";String pathAndName = downPath + fileName;File file = new File(pathAndName);if (file.canRead()) {file.delete();}FileOutputStream out = null;out = new FileOutputStream(pathAndName, true);} catch (FileNotFoundException e) {e.printStackTrace();}try {hdt.write(ostream);} catch (IOException e) {e.printStackTrace();}//输出字节流try {out.write(ostream.toByteArray());} catch (IOException e) {e.printStackTrace();}try {out.close();} catch (IOException e) {e.printStackTrace();}try {ostream.close();} catch (IOException e) {e.printStackTrace();}}/***实现对word读取和修改操作(输出文件流下载方式)*@param response响应,设置生成的文件类型,文件头编码方式和文件名,以及输出*@param filePathword模板路径和名称*@param map待填充的数据,从数据库读取*/publicstaticvoid readwriteWord(HttpServletResponse response, String filePath, Map<String, String> map) {//读取word模板文件//String fileDir = newFile(base.getFile(),"//.. /doc/").getCanonicalPath();//FileInputStream in = new FileInputStream(newFile(fileDir+"/laokboke.doc"));FileInputStream in;HWPFDocument hdt = null;in = new FileInputStream(new File(filePath));hdt = new HWPFDocument(in);} catch (Exception e1) {e1.printStackTrace();}Fields fields = hdt.getFields();Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN) .iterator();while (it.hasNext()) {System.out.println(it.next().getType());}//替换读取到的word模板内容的指定字段Range range = hdt.getRange();for (Map.Entry<String, String> entry : map.entrySet()) { range.replaceText("$" + entry.getKey() + "$",entry.getValue());}//输出word内容文件流,提供下载response.reset();response.setContentType("application/x-msdownload");String fileName = "" + System.currentTimeMillis() + ".doc";response.addHeader("Content-Disposition", "attachment;filename="+ fileName);ByteArrayOutputStream ostream = new ByteArrayOutputStream();OutputStream servletOS = null;try {servletOS = response.getOutputStream();hdt.write(ostream);servletOS.write(ostream.toByteArray());servletOS.flush();servletOS.close();} catch (Exception e) {e.printStackTrace();}}}注:以上代码需要poi包, 可以下载。

利用word模板输出word文件并将文档显示在wpf窗口上

利用word模板输出word文件并将文档显示在wpf窗口上

利⽤word模板输出word⽂件并将⽂档显⽰在wpf窗⼝上⼀、通过模板输出⽂档添加对Microsoft.Office.Interop.Word库的引⽤,需要安装office软件通过⽂本域对需要替换的数据进⾏代换public static bool FillData(string MuBanFileName, string JSSFileName, Hashtable data){try{//Document doc = copyWordDoc(MuBanFileName);File.Copy(MuBanFileName, JSSFileName);ReplaceWordDocAndSave( JSSFileName, data);}catch (Exception){return false;}return true;}protected static void ReplaceWordDocAndSave( object savePath, Hashtable table){object format = WdSaveFormat.wdFormatDocument;object readOnly = false;object isVisible = false;Object Nothing = System.Reflection.Missing.Value;Microsoft.Office.Interop.Word.Application wordApp = new ApplicationClass();//Microsoft.Office.Interop.Word.Document oDoc = wordApp.Documents.Open(ref obj, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, re Microsoft.Office.Interop.Word.Document oDoc=null;try{oDoc = wordApp.Documents.Open(ref savePath, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, object FindText, ReplaceWith, Replace;object MissingValue = Type.Missing;foreach (string str in table.Keys){oDoc.Content.Find.Text = str;//要查找的⽂本FindText = str;//替换⽂本ReplaceWith = Convert.ToString(table[str]);Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;//移除Find的搜索⽂本和段落格式设置oDoc.Content.Find.ClearFormatting();oDoc.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref ReplaceWith, ref Replace, ref}oDoc.SaveAs(ref savePath, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);}catch (Exception){}finally {oDoc.Close(ref Nothing, ref Nothing, ref Nothing);//关闭wordApp组件对象wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);}}⼆、通过documentview控件在wpf窗⼝中加载出来实现⽅式是通过将word⽂档修改为xps⽂档,然后在documentView控件中加载private void ConvertWordToXPS(string wordDocName){FileInfo fi = new FileInfo(wordDocName);XpsDocument result = null;string xpsDocName = bine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), );xpsDocName = xpsDocName.Replace(".docx", ".xps").Replace(".doc", ".xps");Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();try{wordApplication.Documents.Add(wordDocName);Document doc = wordApplication.ActiveDocument;doc.ExportAsFixedFormat(xpsDocName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent,result = new XpsDocument(xpsDocName, FileAccess.Read);}catch (Exception ex){string error = ex.Message;wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);MessageBox.Show(ex.Message);}wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);documentViewer.Document = result.GetFixedDocumentSequence();documentViewer.FitToWidth();result.Close();//File.Delete(xpsDocName);File.Delete(wordDocName);MessageBox.Show("计算完成");//return result;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

java 根据word模板生成word
文件
Java可以使用Apache POI库来生成Word文件,并且也可以使用freemarker等模板引擎来实现根据Word模板生成Word 文件的功能。

下面是一个简单的示例代码,可以帮助您快速入门。

模板制作:offer,wps都行,我使用wps进行操作
第一步制作模板
CTRL+f9生成域------》鼠标右键编辑域------》选择邮件合并-----》在域代码后面加上英文${跟代码内的一致}。

这样模板就创建好了。

首先需要引入POI和freemarker的依赖:
<!-- Apache POI --><dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.core</art
ifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document< /artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template< /artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document.
docx</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.
freemarker</artifactId>
<version>2.0.2</version>
</dependency>
接下来是一个简单的示例代码:
public class WordGenerator {
public static void main(String[] args) throws IOException, TemplateException {
// 读取Word模板
try {
= null;//word
InputStream in = new (new File("模板文件.docx"));
//注册xdocreport实例并加载FreeMarker模板引擎
IXDocReport r = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Freemarker);
// 生成Word文件
//创建xdocreport上下文对象
IContext context =
r.createContext();
//将需要替换的数据数据添加到上下文中
//其中key为word模板中的域名,value是需要替换的值
User user = new User("zhangsan", 18, "福建泉州");
context.put("uesrname",
user.getUsername());
context.put("age", user.getAge()); context.put("address",
user.getAddress());
out = new (new
File("D://xxx.docx"));
//处理word文档并输出
r.process(context, out);
} catch (
IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在这个示例代码中,我们读取了名为模板文件.docx的Word 模板,然后准备了一些数据,利用Freemarker模板引擎将数据填充到模板中,最后生成了一个名为xxx.docx的Word文件。

在实际应用中,您需要根据具体的需求修改模板和数据,并且也可以添加更多的段落、表格、图片等内容。

最后生成:
主要用于批量操作,这里的数据仅供测试。

相关文档
最新文档