java操作word书签生成word模板不用jar包

合集下载

JAVA调用模版生成WORD文件

JAVA调用模版生成WORD文件

* @param newText
*
String 替换为文本
*/
public void replace(Dispatch selection, String newText)
{
//设置替换文本
Dispatch.put(selection, "Text", newText);
}
/**
* 全局替换
*
* @param selection
private Dispatch documents;
private Dispatch selection;
/** * 构造函数 */
public JavaToword() {
saveOnExit = true; if(word==null){ word = new ActiveXComponent("Word.Application");
public Dispatch select() {
return word.getProperty("Selection").toDispatch(); }
/**
* 把插入点移动到文件首位置
*
* @param selection
*
Dispatch 插入点
*/
public void moveStart(Dispatch selection)
Dispatch.call(document, "PrintOut");
Dispatch.call(document, "Close", new Variant(false)); objWord.invoke("Quit",new Variant[0]); word.invoke("Quit",new Variant[0]);

java导出数据为word文档(保持模板格式)

java导出数据为word文档(保持模板格式)

java导出数据为word⽂档(保持模板格式)导出数据到具体的word⽂档⾥⾯,word有⼀定的格式,需要保持不变这⾥使⽤freemarker来实现:①:设计好word⽂档格式,需要⽤数据填充的地⽅⽤便于识别的长字符串替换如 aaaaaaaaaaaaaaaa②:将word⽂档另存为 2003 xml格式③:找到需要替换的地⽅,如将 aaaaaaaaaaaa 修改为 ${userName}如果是list展⽰,注意按照如下⽅式修改:<#list list1 as list1Item>XXXXXXXXXXXXXXXXXX 原有格式代码如⼀⾏数据或者⼀个单元格</#list>④:替换完成后,将xml⽂件后缀修改为ftljava代码如下:package com.xiao;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Main {public static void main(String[] args) throws UnsupportedEncodingException {Map<String, Object> dataMap = new HashMap<String, Object>();dataMap.put("name", "肖昌伟");dataMap.put("depart", "云平台");dataMap.put("date", "2016年"); //列表数据封装List<String> list1 = new ArrayList<String>();list1.add("itema");list1.add("itemb");list1.add("itemc");dataMap.put("list1", list1);DocumentHandler mdoc = new DocumentHandler();mdoc.createDoc(dataMap, "E:/outFile2.doc");}}package com.xiao;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.io.Writer;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;public class DocumentHandler {private Configuration configuration = null;public DocumentHandler() {configuration = new Configuration();configuration.setDefaultEncoding("utf-8");}public void createDoc(Map<String, Object> dataMap, String fileName) throws UnsupportedEncodingException {//需要导出模板的包路径configuration.setClassForTemplateLoading(this.getClass(), "/com/xiao");Template t = null;try {t = configuration.getTemplate("template.ftl");} catch (IOException e) {e.printStackTrace();}File outFile = new File(fileName);Writer out = null;FileOutputStream fos = null;try {fos = new FileOutputStream(outFile);OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");out = new BufferedWriter(oWriter);} catch (FileNotFoundException e1) {e1.printStackTrace();}try {t.process(dataMap, out);out.close();fos.close();} catch (TemplateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}System.out.println("⽂档导出完成");}}这样就可以看到填充好了数据的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⽂档Java使⽤模板导出word⽂档需要导⼊freemark的jar包1. 使⽤word模板,在需要填值的地⽅使⽤字符串代替,是因为word转换为xml⽂件时查找不到要填⼊内容的位置。

尽量不要在写字符串的时候就加上${},xml⽂件会让它和字符串分离。

⽐如:姓名| name2. 填充完之后,把word⽂件另存为xml⽂件,然后使⽤notepad 等编辑软件打开,打开之后代码很多,也很乱,根本看不懂,其实也不⽤看懂哈,搜索找到你要替换的位置的字符串,⽐如name,然后加上${},变成${name}这样,然后就可以保存了,之后把保存的⽂件名后缀替换为.ftl。

模板就ok了。

3. 有个注意事项,这⾥的值⼀定不可以为空,否则会报错,freemark有判断为空的语句,这⾥⽰例⼀个,根据个⼈需求,意思是判断name是否为空,trim之后的lenth是否⼤于0:<#if name?default("")?trim?length gt 0><w:t>${name}</w:t></#if>4. 如果在本地的话可以直接下载下来,但是想要在通过前端下载的话那就需要先将⽂件下载到本地,当作临时⽂件,然后在下载⽂件。

接下来上代码,⽰例:public void downloadCharge(String name, HttpServletRequest request, HttpServletResponse response) {Map<String, Object> map = new HashMap<>();map.put("name", name);Configuration configuration = new Configuration();configuration.setDefaultEncoding("utf-8");try { //模板存放位置InputStream inputStream = this.getClass().getResourceAsStream("/template/report/XXX.ftl");Template t = new Template(null, new InputStreamReader(inputStream));String filePath = "tempFile/";//导出⽂件名String fileName = "XXX.doc";//⽂件名和路径不分开写的话createNewFile()会报错File outFile = new File(filePath + fileName);if (!outFile.getParentFile().exists()) {outFile.getParentFile().mkdirs();}if (!outFile.exists()) {outFile.createNewFile();}Writer out = null;FileOutputStream fos = null;fos = new FileOutputStream(outFile);OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");//这个地⽅对流的编码不可或缺,使⽤main()单独调⽤时,应该可以,但是如果是web请求导出时导出后word⽂档就会打不开,并且包XML⽂件错误。

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。

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文档使用JACOB和POI操作word,Excel,PPT需要的jar包

Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

Java操作word⽂档使⽤JACOB和POI操作word,Excel,PPT需要的jar包可参考⽂档:下载jar包如上是jacob-1.17-M2.jar对应的jar包和dll⽂件....但是我在maven仓库中并没有发现jacob-1.17版本的.所以如果使⽤maven项⽬的话推荐下载jacob-1.14版本的jar包和dll⽂件.使⽤⽅式:import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Arrays;import com.jacob.activeX.ActiveXComponent;public class WriteDoc2 {public static void main(String[] args) {//在正式批量跑之前,做单个word⽂档的测试.WordUtils util = new WordUtils(true);util.openDocument("C:\\Users\\ABC\\Desktop\\test.docx");util.setSaveOnExit(true);util.insertText("xxx444dddd4x");util.saveAs("C:\\Users\\ABC\\Desktop\\test.docx");util.closeDocument();}}对应WordUtils.java⼯具类,我是使⽤的如下:import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;public class WordUtils {// word运⾏程序对象private ActiveXComponent word;// 所有word⽂档集合private Dispatch documents;// word⽂档private Dispatch doc;// 选定的范围或插⼊点private Dispatch selection;// 保存退出private boolean saveOnExit;public WordUtils(boolean visible) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));documents = word.getProperty("Documents").toDispatch();}/*** 设置退出时参数** @param saveOnExit* boolean true-退出时保存⽂件,false-退出时不保存⽂件 */public void setSaveOnExit(boolean saveOnExit) {this.saveOnExit = saveOnExit;}/*** 创建⼀个新的word⽂档*/public void createNewDocument() {doc = Dispatch.call(documents, "Add").toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个已经存在的word⽂档** @param docPath*/public void openDocument(String docPath) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个有密码保护的word⽂档* @param docPath* @param password*/public void openDocument(String docPath, String password) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();unProtect(password);selection = Dispatch.get(word, "Selection").toDispatch();}/*** 去掉密码保护* @param password*/public void unProtect(String password){try{String protectionType = Dispatch.get(doc, "ProtectionType").toString();if(!"-1".equals(protectionType)){Dispatch.call(doc, "Unprotect", password);}}catch(Exception e){e.printStackTrace();}}/*** 添加密码保护* @param password*/public void protect(String password){String protectionType = Dispatch.get(doc, "ProtectionType").toString();if("-1".equals(protectionType)){Dispatch.call(doc, "Protect",new Object[]{new Variant(3), new Variant(true), password});}}/*** 显⽰审阅的最终状态*/public void showFinalState(){Dispatch.call(doc, "AcceptAllRevisionsShown");}/*** 打印预览:*/public void printpreview() {Dispatch.call(doc, "PrintPreView");}/*** 打印*/public void print(){Dispatch.call(doc, "PrintOut");}public void print(String printerName) {word.setProperty("ActivePrinter", new Variant(printerName));print();}/*** 指定打印机名称和打印输出⼯作名称* @param printerName* @param outputName*/public void print(String printerName, String outputName){word.setProperty("ActivePrinter", new Variant(printerName));Dispatch.call(doc, "PrintOut", new Variant[]{new Variant(false), new Variant(false), new Variant(0), new Variant(outputName)}); }/*** 把选定的内容或插⼊点向上移动** @param pos*/public void moveUp(int pos) {move("MoveUp", pos);}/*** 把选定的内容或者插⼊点向下移动** @param pos*/public void moveDown(int pos) {move("MoveDown", pos);}/*** 把选定的内容或者插⼊点向左移动** @param pos*/public void moveLeft(int pos) {move("MoveLeft", pos);}/*** 把选定的内容或者插⼊点向右移动** @param pos*/public void moveRight(int pos) {move("MoveRight", pos);}/*** 把选定的内容或者插⼊点向右移动*/public void moveRight() {Dispatch.call(getSelection(), "MoveRight");}/*** 把选定的内容或者插⼊点向指定的⽅向移动* @param actionName* @param pos*/private void move(String actionName, int pos) {for (int i = 0; i < pos; i++)Dispatch.call(getSelection(), actionName);}/*** 把插⼊点移动到⽂件⾸位置*/public void moveStart(){Dispatch.call(getSelection(), "HomeKey", new Variant(6));}/*** 把插⼊点移动到⽂件末尾位置*/public void moveEnd(){Dispatch.call(getSelection(), "EndKey", new Variant(6));}/*** 插⼊换页符*/public void newPage(){Dispatch.call(getSelection(), "InsertBreak");}public void nextPage(){moveEnd();moveDown(1);}public int getPageCount(){Dispatch selection = Dispatch.get(word, "Selection").toDispatch();return Dispatch.call(selection,"information", new Variant(4)).getInt(); }/*** 获取当前的选定的内容或者插⼊点* @return当前的选定的内容或者插⼊点*/public Dispatch getSelection(){if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();return selection;}/*** 从选定内容或插⼊点开始查找⽂本* @param findText 要查找的⽂本* @return boolean true-查找到并选中该⽂本,false-未查找到⽂本*/public boolean find(String findText){if(findText == null || findText.equals("")){return false;}// 从selection所在位置开始查询Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();// 设置要查找的内容Dispatch.put(find, "Text", findText);// 向前查找Dispatch.put(find, "Forward", "True");// 设置格式Dispatch.put(find, "Format", "True");// ⼤⼩写匹配Dispatch.put(find, "MatchCase", "True");// 全字匹配Dispatch.put(find, "MatchWholeWord", "True");// 查找并选中return Dispatch.call(find, "Execute").getBoolean();}/*** 查找并替换⽂字* @param findText* @param newText* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceText(String findText, String newText){moveStart();if (!find(findText))return false;Dispatch.put(getSelection(), "Text", newText);return true;}/*** 进⼊页眉视图*/public void headerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "9");}/*** 进⼊页脚视图*/public void footerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "10");}/*** 进⼊普通视图*/public void pageView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", new Variant(0));//普通视图}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText){int count = getPageCount();for(int i = 0; i < count; i++){headerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveEnd();}footerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}pageView();moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}nextPage();}}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText, String fontName, int size){ /****插⼊页眉页脚*****///取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();/****设置页眉*****/Dispatch.put(view, "SeekView", "9");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}/****设置页脚*****/Dispatch.put(view, "SeekView", "10");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}Dispatch.put(view, "SeekView", new Variant(0));//恢复视图moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);putFontSize(getSelection(), fontName, size);moveStart();}}/*** 设置选中或当前插⼊点的字体* @param selection* @param fontName* @param size*/public void putFontSize(Dispatch selection, String fontName, int size){Dispatch font = Dispatch.get(selection, "Font").toDispatch();Dispatch.put(font, "Name", new Variant(fontName));Dispatch.put(font, "Size", new Variant(size));}/*** 在当前插⼊点插⼊字符串*/public void insertText(String text){Dispatch.put(getSelection(), "Text", text);}/*** 将指定的⽂本替换成图⽚* @param findText* @param imagePath* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceImage(String findText, String imagePath, int width, int height){moveStart();if (!find(findText))return false;Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();return true;}/*** 全局将指定的⽂本替换成图⽚* @param findText* @param imagePath*/public void replaceAllImage(String findText, String imagePath, int width, int height){moveStart();while (find(findText)){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveStart();}}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath, int width, int height){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath){Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 获取书签的位置* @param bookmarkName* @return书签的位置*/public Dispatch getBookmark(String bookmarkName){try{Dispatch bookmark = Dispatch.call(this.doc, "Bookmarks", bookmarkName).toDispatch();return Dispatch.get(bookmark, "Range").toDispatch();}catch(Exception e){e.printStackTrace();}return null;}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath*/public void insertImageAtBookmark(String bookmarkName, String imagePath){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath* @param width* @param height*/public void insertImageAtBookmark(String bookmarkName, String imagePath, int width, int height){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null){Dispatch picture = Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));}}/*** 在指定的书签位置插⼊⽂本* @param bookmarkName* @param text*/public void insertAtBookmark(String bookmarkName, String text){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.put(dispatch, "Text", text);}/*** ⽂档另存为* @param savePath*/public void saveAs(String savePath){Dispatch.call(doc, "SaveAs", savePath);}/*** ⽂档另存为PDF* <b><p>注意:此操作要求word是2007版本或以上版本且装有加载项:Microsoft Save as PDF 或 XPS</p></b>* @param savePath*/public void saveAsPdf(String savePath){Dispatch.call(doc, "SaveAs", new Variant(17));}/*** 保存⽂档* @param savePath*/public void save(String savePath){Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);}/*** 关闭word⽂档*/public void closeDocument(){if (doc != null) {Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}public void exit(){word.invoke("Quit", new Variant[0]);}}具体WordUtils类的使⽤暂时没有看到更多的例⼦,上⾯的util的使⽤是⾃⼰摸索出来的,可能不是最优,最恰当的.//==================================================================================================使⽤Java⼯具POI操作MicroSoft Office套件Word,Excle和PPT使⽤Maven⼯程的话需要在Pom.xml⽂件中引⼊的jar包.⼀开始是想使⽤POI⼯具操作,但是从⽹上找来的代码始终报编译错误,代码中的⼀些类找不到,但是也明明已经引⼊了poi-3.x.jar包⽂件,更换了好⼏个poi版本的jar包仍是⼀样的效果.随后调查,到底需要哪些jar包.....结果如下:<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>2.3.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.8</version></dependency>所依赖的全部jar包的截图如果只引⼊⼀个poi-3.x.jar包是会报错的. POI具体操作Word,Excel,和PPT的代码,⾃⾏百度.只要jar包引⼊的正确,运⾏编译代码就没有问题.。

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包, 可以下载。

Java模板动态生成word文件的方法步骤

Java模板动态生成word文件的方法步骤

Java模板动态⽣成word⽂件的⽅法步骤最近项⽬中需要根据模板⽣成word⽂档,模板⽂件也是word⽂档。

当时思考⼀下想⽤POI API来做,但是觉得⽤起来相对复杂。

后来⼜找了⼀种⽅式,使⽤freemarker模板⽣成word⽂件,经过尝试觉得还是相对简单易⾏的。

使⽤freemarker模板⽣成word⽂档主要有这么⼏个步骤1、创建word模板:因为我项⽬中⽤到的模板本⾝是word,所以我就直接编辑word⽂档转成freemarker(.ftl)格式的。

2、将改word⽂件另存为xml格式,注意使⽤另存为,不是直接修改扩展名。

3、将xml⽂件的扩展名改为ftl4、编写java代码完成导出使⽤到的jar:freemarker.jar (2.3.28) ,其中Configuration对象不推荐直接new Configuration(),仔细看Configuration.class⽂件会发现,推荐的是 Configuration(Version incompatibleImprovements) 这个构造⽅法,具体这个构造⽅法⾥⾯传的就是Version版本类,⽽且版本号不能低于2.3.0闲⾔碎语不再讲,直接上代码public static void exportDoc() {String picturePath = "D:/image.png";Map<String, Object> dataMap = new HashMap<String, Object>();dataMap.put("brand", "海尔");dataMap.put("store_name", "海尔天津");dataMap.put("user_name", "⼩明");//经过编码后的图⽚路径String image = getWatermarkImage(picturePath);dataMap.put("image", image);//Configuration⽤于读取ftl⽂件Configuration configuration = new Configuration(new Version("2.3.0"));configuration.setDefaultEncoding("utf-8");Writer out = null;try {//输出⽂档路径及名称File outFile = new File("D:/导出优惠证明.doc");out = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(new File("outFile")), "utf-8"), 10240);} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();}// 加载⽂档模板Template template = null;try {//指定路径,例如C:/a.ftl 注意:此处指定ftl⽂件所在⽬录的路径,⽽不是ftl⽂件的路径configuration.setDirectoryForTemplateLoading(new File("C:/"));//以utf-8的编码格式读取⽂件template = configuration.getTemplate("导出优惠证明.ftl", "utf-8");} catch (IOException e) {e.printStackTrace();throw new RuntimeException("⽂件模板加载失败!", e);}// 填充数据try {template.process(dataMap, out);} catch (TemplateException e) {e.printStackTrace();throw new RuntimeException("模板数据填充异常!", e);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("模板数据填充异常!", e);} finally {if (null != out) {try {out.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException("⽂件输出流关闭异常!", e);}}}}因为很多时候我们根据模板⽣成⽂件需要添加⽔印,也就是插⼊图⽚/**** 处理图⽚* @param watermarkPath 图⽚路径 D:/image.png* @return*/private String getWatermarkImage(String watermarkPath) {InputStream in = null;byte[] data = null;try {in = new FileInputStream(watermarkPath);data = new byte[in.available()];in.read(data);in.close();} catch (Exception e) {e.printStackTrace();}BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);}注意点:插⼊图⽚后的word转化为ftl模板⽂件(ps:⽔印图⽚可以在word上调整到⾃⼰想要的⼤⼩,然后在执⾏下⾯的步骤)1、先另存为xml2、将xml扩展名改为ftl3、打开ftl⽂件, 搜索w:binData 或者 png可以快速定位图⽚的位置,图⽚已经编码成0-Z的字符串了, 如下:5、将上述0-Z的字符串全部删掉,写上${image}(变量名随便写,跟dataMap⾥的key保持⼀致)后保存6、也是创建⼀个Map, 将数据存到map中,只不过我们要把图⽚⽤代码进⾏编码,将其也编成0-Z的字符串,代码请看上边⾄此⼀个简单的按照模板⽣成word并插⼊图⽚(⽔印)功能基本完成。

java 根据word模板生成word文件

java 根据word模板生成word文件

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</artifactId><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;//wordInputStream 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 (newFile("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文件。

Javafreemarker生成word模板文件(如合同文件)及转pdf文件方法

Javafreemarker生成word模板文件(如合同文件)及转pdf文件方法

Javafreemarker⽣成word模板⽂件(如合同⽂件)及转pdf⽂件⽅法Java freemarker⽣成word模板⽂件(如合同⽂件)及转pdf⽂件⽅法创建模板⽂件ContractTemplate.docxContractTemplate.xml导⼊的Jar包compile("junit:junit")compile("org.springframework:spring-test")compile("org.springframework.boot:spring-boot-test")testCompile 'org.springframework.boot:spring-boot-starter-test'compile 'org.freemarker:freemarker:2.3.28'compile 'fakepath:aspose-words:19.5jdk'compile 'fakepath:aspose-cells:8.5.2'Java⼯具类 xml⽂档转换 Word XmlToDocx.javapackage com.test.docxml.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;/*** xml⽂档转换 Word*/public class XmlToDocx {/**** @param documentFile 动态⽣成数据的docunment.xml⽂件* @param docxTemplate docx的模板* @param toFilePath 需要导出的⽂件路径* @throws Exception*/public static void outDocx(File documentFile, String docxTemplate, String toFilePath,String key) throws Exception { try {File docxFile = new File(docxTemplate);ZipFile zipFile = new ZipFile(docxFile);Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();FileOutputStream fileOutputStream = new FileOutputStream(toFilePath);ZipOutputStream zipout = new ZipOutputStream(fileOutputStream);int len = -1;byte[] buffer = new byte[1024];while (zipEntrys.hasMoreElements()) {ZipEntry next = zipEntrys.nextElement();InputStream is = zipFile.getInputStream(next);// 把输⼊流的⽂件传到输出流中如果是word/document.xml由我们输⼊zipout.putNextEntry(new ZipEntry(next.toString()));if ("word/document.xml".equals(next.toString())) {InputStream in = new FileInputStream(documentFile);while ((len = in.read(buffer)) != -1) {zipout.write(buffer, 0, len);}in.close();} else {while ((len = is.read(buffer)) != -1) {zipout.write(buffer, 0, len);}is.close();}}zipout.close();} catch (Exception e) {e.printStackTrace();}}}Java⼯具类 word⽂档转换 PDF WordToPdf.javapackage com.test.docxml.utils;import com.aspose.cells.*;import com.aspose.cells.License;import com.aspose.words.*;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;/*** word⽂档转换 PDF*/public class WordToPdf {/*** 获取license许可凭证* @return*/private static boolean getLicense() {boolean result = false;try {String licenseStr = "<License>\n"+ " <Data>\n"+ " <Products>\n"+ " <Product>Aspose.Total for Java</Product>\n"+ " <Product>Aspose.Words for Java</Product>\n"+ " </Products>\n"+ " <EditionType>Enterprise</EditionType>\n"+ " <SubscriptionExpiry>20991231</SubscriptionExpiry>\n"+ " <LicenseExpiry>20991231</LicenseExpiry>\n"+ " <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n"+ " </Data>\n"+ " <Signature>0nRuwNEddXwLfXB7pw66G71MS93gW8mNzJ7vuh3Sf4VAEOBfpxtHLCotymv1PoeukxYe31K441Ivq0Pkvx1yZZG4O1KCv3Omdbs7uqzUB4xXHlOub4VsTODzDJ5MWHqlRCB1HHcGjlyT2sVGiovLt0Grvqw5+QXBuin + "</License>";InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));License asposeLic = new License();asposeLic.setLicense(license);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** word⽂档转换为 PDF* @param inPath 源⽂件* @param outPath ⽬标⽂件*/public static File doc2pdf(String inPath, String outPath) {//验证License,获取许可凭证if (!getLicense()) {return null;}//新建⼀个PDF⽂档File file = new File(outPath);try {//新建⼀个IO输出流FileOutputStream os = new FileOutputStream(file);//获取将要被转化的word⽂档Document doc = new Document(inPath);// 全⾯⽀持DOC, DOCX,OOXML, RTF HTML,OpenDocument,PDF, EPUB, XPS,SWF 相互转换doc.save(os, com.aspose.words.SaveFormat.PDF);os.close();} catch (Exception e) {e.printStackTrace();}return file;}public static void main(String[] args) {doc2pdf("D:/1.doc", "D:/1.pdf");}}Java单元测试类 XmlDocTest.javapackage com.test.docxml;import com.test.docxml.utils.WordToPdf;import com.test.docxml.utils.XmlToDocx;import freemarker.template.Configuration;import freemarker.template.Template;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import java.io.File;import java.io.PrintWriter;import java.io.Writer;import java.nio.charset.Charset;import java.util.HashMap;import java.util.Locale;import java.util.Map;/*** 本地单元测试*/@RunWith(SpringJUnit4ClassRunner.class)//@RunWith(SpringRunner.class)@SpringBootTest(classes= TemplateApplication.class)@WebAppConfigurationpublic class XmlDocTest {//短租@Testpublic void testContract() throws Exception{String contractNo = "1255445544";String contractCorp = "银河宇宙⽆敌测试soft";String contractDate = "2022-01-27";String contractItem = "房地产交易中⼼";String contractContent = "稳定发展中的⽂案1万字";//doc xml模板⽂件String docXml = "ContractTemplate.xml"; //使⽤替换内容//xml中间临时⽂件String xmlTemp = "tmp-ContractTemplate.xml";//⽣成⽂件的doc⽂件String toFilePath = contractNo + ".docx";//模板⽂档String docx = "ContractTemplate.docx";//⽣成pdf⽂件String toPdfFilePath = contractNo + ".pdf";;String CONTRACT_ROOT_URL = "/template";Resource contractNormalPath = new ClassPathResource(CONTRACT_ROOT_URL + File.separator + docXml);String docTemplate = contractNormalPath.getURI().getPath().replace(docXml, docx);//设置⽂件编码(注意点1)Writer writer = new PrintWriter(new File(xmlTemp),"UTF-8");Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);configuration.setEncoding(Locale.CHINESE, Charset.forName("UTF-8").name());//设置配置(注意点3)configuration.setDefaultEncoding("UTF-8");String filenametest = contractNormalPath.getURI().getPath().replace(docXml, "");System.out.println("filenametest=" + filenametest);configuration.setDirectoryForTemplateLoading(new File(filenametest));// Template template = configuration.getTemplate(ContractConstants.CONTRACT_NORMAL_URL+orderType+type+".xml"); //设置模板编码(注意点2)Template template = configuration.getTemplate(docXml,"UTF-8"); //绝对地址Map paramsMap = new HashMap();paramsMap.put("contractCorp",contractCorp);paramsMap.put("contractDate",contractDate);paramsMap.put("contractNo",contractNo);paramsMap.put("contractItem",contractItem);paramsMap.put("contractContent",contractContent);template.process(paramsMap, writer);XmlToDocx.outDocx(new File(xmlTemp), docTemplate, toFilePath, null);System.out.println("do finish");//转成pdfWordToPdf.doc2pdf(toFilePath,toPdfFilePath);}}创建成功之后的⽂件如下:。

idea javadoc文档的生成方法

idea javadoc文档的生成方法

idea javadoc文档的生成方法【实用版3篇】目录(篇1)1.介绍 JavaDoc 文档2.JavaDoc 文档的生成方法3.使用 IDEA 自动生成 JavaDoc 文档4.手动编写 JavaDoc 文档5.结论正文(篇1)一、介绍 JavaDoc 文档JavaDoc 是 Java 开发中的一种文档编写标准,它可以描述 Java 类、方法、成员变量等的详细信息。

JavaDoc 文档通常以 HTML 格式生成,并且可以被 IDEA 等 Java 开发工具自动生成。

二、JavaDoc 文档的生成方法JavaDoc 文档的生成方法主要有两种:使用 IDEA 自动生成和手动编写。

1.使用 IDEA 自动生成 JavaDoc 文档IDEA 是一款强大的 Java 开发工具,它可以自动生成 JavaDoc 文档。

具体操作步骤如下:(1)打开 IDEA,导入 Java 项目。

(2)在项目中选择需要生成 JavaDoc 的类或方法,右键点击,选择“生成 JavaDoc”。

(3)IDEA 会自动生成 JavaDoc 文档,并将其保存在项目指定的输出目录中。

2.手动编写 JavaDoc 文档手动编写 JavaDoc 文档需要遵循一定的规范,例如使用特定的注释标签、指定文档生成工具等。

下面是一个简单的手动编写 JavaDoc 文档的示例:```java/*** 这是一个简单的 JavaDoc 注释* @author YourName* @version 1.0* @since JDK 1.8*/public class MyClass {// 类的成员变量和方法}```三、结论JavaDoc 文档是 Java 开发中重要的文档之一,它可以帮助开发者更好地理解和使用 Java 类、方法等。

使用 IDEA 可以方便地生成 JavaDoc 文档,而手动编写 JavaDoc 文档则需要遵循一定的规范。

目录(篇2)1.介绍 Javadoc2.Javadoc 的生成方法3.Javadoc 生成文档的步骤4.常见问题与解决方法5.总结正文(篇2)一、介绍 JavadocJavadoc 是 Java 开发中的一种文档生成工具,它可以从 Java 源代码中提取类、方法、成员变量等信息,并生成 HTML 格式的文档。

java生成word

java生成word

java⽣成word当我们使⽤Java⽣成word⽂档时,通常⾸先会想到iText和POI,这是因为我们习惯了使⽤这两种⽅法操作Excel,⾃然⽽然的也想使⽤这种⽣成word⽂档。

但是当我们需要动态⽣成word时,通常不仅要能够显⽰word中的内容,还要能够很好的保持word中的复杂样式。

这时如果再使⽤IText和POI去操作,就好⽐程序员去搬砖⼀样痛苦。

这时候,我们应该考虑使⽤FreeMarker的模板技术快速实现这个复杂的功能,让程序员在喝咖啡的过程中就把问题解决。

实现思路是这样的:先创建⼀个word⽂档,按照需求在word中填好⼀个模板,然后把对应的数据换成变量${},然后将⽂档保存为xml⽂档格式,使⽤⽂档编辑器打开这个xml格式的⽂档,去掉多余的xml符号,使⽤Freemarker读取这个⽂档然后替换掉变量,输出word⽂档即可。

具体过程如下:1.创建带有格式的word⽂档,将该需要动态展⽰的数据使⽤变量符替换。

2. 将刚刚创建的word⽂档另存为xml格式。

3.编辑这个XMl⽂档去掉多余的xml标记,如图中蓝⾊部分 4.从官⽹最新的开发包,将freemarker.jar拷贝到⾃⼰的开发项⽬中。

5.新建DocUtil类,实现根据Doc模板⽣成word⽂件的⽅法1234 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36package com.favccxx.secret.util;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.DefaultObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateExceptionHandler;public class DocUtil {privateConfiguration configure = null;publicDocUtil(){configure= new Configuration();configure.setDefaultEncoding("utf-8");}/*** 根据Doc模板⽣成word⽂件* @param dataMap Map 需要填⼊模板的数据* @param fileName ⽂件名称* @param savePath 保存路径*/publicvoid createDoc(Map<String, Object> dataMap, String downloadType, StringsavePath){try{//加载需要装填的模板Templatetemplate = null;//加载模板⽂件configure.setClassForTemplateLoading(this.getClass(),"/com/favccxx/secret/templates"); //设置对象包装器configure.setObjectWrapper(newDefaultObjectWrapper());//设置异常处理器configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); //定义Template对象,注意模板类型名字与downloadType要⼀致template= configure.getTemplate(downloadType + ".xml");//输出⽂档FileoutFile = new File(savePath);Writerout = null;3637 38 39 40 41 42 43 44 45 46 out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8")); template.process(dataMap,out);outFile.delete();}catch(Exception e) {e.printStackTrace();}}} 6.⽤户根据⾃⼰的需要,调⽤使⽤getDataMap获取需要传递的变量,然后调⽤createDoc⽅法⽣成所需要的⽂档。

java生成word文件并下载

java生成word文件并下载

java生成word文件并下载importjava.io.BufferedInputStream;importjava.io.BufferedOutp utStream;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream ;importjava.io.IOE某ception;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.OutputStreamWriter;importjava.io.Writer;.URLEncoder;importjava.util.Map;importfreemarker.template.Configuration;importfreemarker.tem plate.Template;/某某publicclaWordUtil{privatetaticLoggerlog=Logger.getLogger(Wor dUtil.cla);/某某//创建配置实例Configurationconfiguration=newConfiguration();//设置编码configuration.etDefaultEncoding(\//ftl模板文件Filefile=newFile(filePath);configuration.etDirectoryForTempl ateLoading(file);//获取模板Templatetemplate=configuration.getTemplate(templateName);//输出文件FileoutFile=newFile(filePath+File.eparator+fileName);//如果输出目标文件夹不存在,则创建if(!outFile.getParentFile().e某it()){outFile.getParentFile().mkdir();}//将模板和数据模型合并生成文件Writerout=newBufferedWriter(newOutputStreamWriter(newFileOutputS tream(outFile),\//生成文件template.proce(dataMap,out);//关闭流out.fluh();out.cloe();}catch(E某ceptione){log.error(\生成word文档(WordUtil)出错:【mg:\】,文件名:\+fileName);}fi.read(buffer);fi.cloe();//清空reponerepone.reet();//设置repone的HeaderStringfileName=URLEncoder.encode(filename,\if(fileName.lengt h()>150){//解决IE6.0bugfileName=newString(filename.getByte(\} repone.addHeader(\repone.addHeader(\OutputStreamtoClient=newBufferedOutputStream(repone.getOutpu tStream());repone.etContentType(\toClient.write(buffer);toClient .fluh();toClient.cloe();file.delete();returnrepone;}。

Java使用word文档模板下载文件(内容为表格)

Java使用word文档模板下载文件(内容为表格)

Java使⽤word⽂档模板下载⽂件(内容为表格)注意:1、此Demo操作的是word的表格2、本次使⽤的word后缀为docx1、pom引⽤jar<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>2、代码import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.util.Units;import ermodel.*;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.core.io.ClassPathResource;import java.io.*;import java.util.HashMap;import java.util.List;import java.util.Map;/*** word模板赋值下载** @author a*/@SpringBootApplicationpublic class ReadResourceApplication {/*** 主⽅法** @param args*/public static void main(String[] args) {SpringApplication.run(ReadResourceApplication.class, args);Map map = new HashMap(3);map.put("${name}", "测试");map.put("${sexName}", "男");map.put("${mzName}", "汉");getBuild("wordXML/领导⼲部基本情况信息表.docx", map, "D:/aaa.doc");}/*** 赋值并下载⽂件** @param tmpFile* @param contentMap* @param exportFile*/public static void getBuild(String tmpFile, Map<String, String> contentMap, String exportFile) {InputStream inputStream = null;try {// 加载Word⽂件inputStream = new ClassPathResource(tmpFile).getInputStream();} catch (IOException e) {e.printStackTrace();}XWPFDocument document = null;try {// 加载流到documentdocument = new XWPFDocument(inputStream);} catch (IOException e) {e.printStackTrace();}// 获取⽂档中的表格List<XWPFTable> tables = document.getTables();for (int j = 0; j < tables.size(); j++) {XWPFTable table = tables.get(j);// 获取表格⾏List<XWPFTableRow> rows = table.getRows();for (int i = 0; i < rows.size(); i++) {// 得到每⼀⾏XWPFTableRow newRow = table.getRow(i);// 得到所有的单元格List<XWPFTableCell> cells = newRow.getTableCells();for (int k = 0; k < cells.size(); k++) {// 得到每⼀列XWPFTableCell cell = cells.get(k);// 以下为更新替换值逻辑List<XWPFParagraph> paragraphs = cell.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {List<XWPFRun> runs = paragraph.getRuns();String cellText = cell.getText();if (contentMap.keySet().contains(cellText)) {for (int m = 0; m < runs.size(); m++) {if (m == runs.size() - 1) {runs.get(m).setText(contentMap.get(cellText), 0);} else {runs.get(m).setText("", 0);}}} else if (cellText.equals("${picture}")) {for (int m = 0; m < runs.size(); m++) {if (m == runs.size() - 1) {try {runs.get(m).setText("", 0);runs.get(m).addPicture(new ClassPathResource("wordXML/培训⼆维码.png").getInputStream(), XWPFDocument.PICTURE_TYPE_PNG, "培训⼆维码.png,", Units.toEMU(200), Units.toEMU(200)); } catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} else {runs.get(m).setText("", 0);}}}}}}}//导出⽂件到磁盘try {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();document.write(byteArrayOutputStream);OutputStream outputStream = new FileOutputStream(exportFile);outputStream.write(byteArrayOutputStream.toByteArray());outputStream.close();} catch (IOException e) {e.printStackTrace();}}}需要更改的地⽅:1、word⽂档路径2、图⽚路径(不需要图⽚的可直接删除相关代码)。

通过Java往word中写入内容

通过Java往word中写入内容

1、向wo‎r d中写入‎内容首‎先在wor‎d中设置书‎签,如书签‎名为boo‎k mark‎,java‎s crip‎t中可以这‎样写v‎a rwor‎d;wo‎r d=ne‎w Acti‎v eXOb‎j ect(‎"Word‎.Appl‎i cati‎o n");‎varr‎a nge=‎w ord.‎R ange‎;wor‎d.Vis‎i ble=‎t rue;‎varp‎a th="‎f ilep‎a th";‎word‎.Docu‎m ents‎.Open‎(path‎);ra‎n ge=w‎o rd.A‎c tive‎D ocum‎e nt.B‎o okma‎r ks("‎b ookm‎a rk")‎.Rang‎e;ra‎n ge.I‎n sert‎B efor‎e("哈哈‎哈哈哈哈"‎);庸‎-人发表于‎2010-‎07-06‎12:4‎8:38Z‎m j一起聊‎2、把w‎o rd文件‎转成htm‎l文件‎<scri‎p tlan‎g uage‎=java‎s crip‎t>fu‎n ctio‎n save‎w ord(‎){va‎r oWor‎d App=‎n ewAc‎t iveX‎O bjec‎t("Wo‎r d.Ap‎p lica‎t ion"‎);va‎r oDoc‎u ment‎=oWor‎d App.‎D ocum‎e nts.‎O pen(‎"C:\\‎d oc2h‎t ml\\‎x.doc‎");o‎D ocum‎e nt.S‎a veAs‎("C:\‎\test‎.htm"‎,8)o‎W ordA‎p p.Qu‎i t();‎}</‎s crip‎t></‎H EAD>‎<BOD‎Y>Cl‎i ckth‎e"sav‎e"but‎t onto‎s avet‎h efil‎e"C:\‎t est.‎d oc"t‎o"C:\‎t est.‎h tm":‎<inp‎u ttyp‎e=but‎t onon‎c lick‎="sav‎e word‎()"va‎l ue=s‎a ve>‎</BO‎D Y><‎/HTML‎>庸-‎人发表于2‎010-0‎7-06 ‎12:53‎:09Zm‎j一起聊‎拷贝tab‎l e1内的‎内容到wo‎r d<‎s crip‎t lang‎u age=‎"java‎s crip‎t">f‎u ncti‎o nOpe‎n Word‎(){//‎导出wor‎dLay‎e r1.s‎t yle.‎b orde‎r=0;‎E xcel‎S heet‎=newA‎c tive‎X Obje‎c t('W‎o rd.A‎p plic‎a tion‎');E‎x celS‎h eet.‎A ppli‎c atio‎n.Vis‎i ble=‎t rue;‎varm‎y doc=‎E xcel‎S heet‎.Docu‎m ents‎.Add(‎'',0,‎0);m‎y Rang‎e=myd‎o c.Ra‎n ge(0‎,1);‎m yRan‎g e=my‎d oc.R‎a nge(‎m yRan‎g e.En‎d-1,m‎y Rang‎e.End‎);//设‎定起始点‎v arse‎l=Lay‎e r1.d‎o cume‎n t.bo‎d y.cr‎e ateT‎e xtRa‎n ge()‎;sel‎.move‎T oEle‎m entT‎e xt(t‎a ble1‎);se‎l.sel‎e ct()‎;Lay‎e r1.d‎o cume‎n t.ex‎e cCom‎m and(‎'Copy‎');s‎e l.mo‎v eEnd‎('cha‎r acte‎r');‎m yRan‎g e.Pa‎s te()‎;my‎R ange‎=mydo‎c.Ran‎g e(my‎R ange‎.End-‎1,myR‎a nge.‎E nd);‎myRa‎n ge.I‎n sert‎A fter‎("\n"‎);Ex‎c elSh‎e et.A‎c tive‎W indo‎w.Vie‎w.Tab‎l eGri‎d line‎s=fal‎s e;}‎</sc‎r ipt>‎庸-人‎发表于20‎10-07‎-06 1‎2:57:‎43Zmj‎一起聊操‎作exce‎l:<‎%@pag‎e c%>‎<h1>c‎o nten‎t</h1‎><ht‎m l><‎h ead>‎<scr‎i ptla‎n guag‎e="ja‎v ascr‎i pt"t‎y pe="‎t ext/‎j avas‎c ript‎">fu‎n ctio‎n Make‎E xcel‎(){v‎a ri,j‎,n;t‎r y{v‎a rxls‎=newA‎c tive‎X Obje‎c t("E‎x cel.‎A ppli‎c atio‎n");‎}cat‎c h(e)‎{ale‎r t("要‎打印该表,‎您必须安装‎E xcel‎电子表格软‎件,同时浏‎览器须使用‎“Acti‎v eX控件‎”,您的浏‎览器须允许‎执行控件。

javapoi实现word导出(包括word模板的使用、复制表格、复制行、插入图片的使用)

javapoi实现word导出(包括word模板的使用、复制表格、复制行、插入图片的使用)
1 2 3 4 5 6 7 8 9 10 11 12 13 4.导出的工具类 /** * 功能描述:word工具类 * * @author jynn *ห้องสมุดไป่ตู้@created 2019年8月15日 * @version 1.0.0 */ public class WordUtil {
/** * 功能描述:word下载 * * @param response * @param patientMap * @param list * @param itemList * @param file * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static final void DownloadWord(HttpServletResponse response, Map<String, Object> patientMap, List<Map<String, Object>> list, List<List<String>> itemList, String file) {
博客园 用户登录 代码改变世界 密码登录 短信登录 忘记登录用户名 忘记密码 记住我 登录 第三方登录/注册 没有账户, 立即注册
javapoi实现 word导出(包括 word模板的使用、复制表格、复制 行、插入图片的使用)
java poi实现数据的word导出(包括word模板的使用、复制表格、复制行、插入图片的使用) 1.实现的效果 实现病人基本信息、多条病历数据、多项检查项图片的动态插入(网络图片)
/** * 功能描述:复制段落,从source到target * * @param target * @param source * @param index * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static void copyParagraph(XWPFParagraph target, XWPFParagraph source, Integer index) { // 设置段落样式 target.getCTP().setPPr(source.getCTP().getPPr()); // 移除所有的run for (int pos = target.getRuns().size() - 1; pos >= 0; pos--) { target.removeRun(pos); } // copy 新的run for (XWPFRun s : source.getRuns()) { XWPFRun targetrun = target.createRun(); copyRun(targetrun, s, index); } }

JAVA操作WORD

JAVA操作WORD

JAVA操作WORDJava操作Word主要有两种方式:一种是使用Apache POI库进行操作,另一种是使用XML模板进行操作。

下面将详细介绍如何通过XML模板实现Java操作Word。

1.准备工作:2. 创建Word模板:首先,创建一个空的Word文档,将其保存为XML格式,作为Word的模板。

可以在Word中添加一些标记或占位符,用于后续替换。

3.导入POI和相关依赖:在Java项目中,导入以下依赖:```xml<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>3.1.0</version></dependency>```4.读取模板文件:使用POI库读取Word模板文件,将其转换为XML格式的字符串,并保存为`template.xml`文件中。

```javaimport ermodel.XWPFDocument;import java.io.FileOutputStream;public class WordTemplateReaderpublic static void main(String[] args) throws ExceptionXWPFDocument document = new XWPFDocument(new FileInputStream("template.docx"));FileOutputStream out = new FileOutputStream("template.xml");document.write(out);out.close(;document.close(;}}```5.数据替换:读取template.xml文件,使用Java中的字符串替换功能,将模板中的占位符替换为实际的数据。

javaweb页面导出word

javaweb页面导出word

javaweb页⾯导出word①我做了⼀个word模板,定义好了书签为listyd,书签是在⼀个表格中,在书签位置动态的⽣成表格,例⼦代码如下:var ole = new ActiveXObject("Word.Application");var url=c:\nsqktzs_fm.doc"var doc =ole.documents.open(url,false,false);ole.V isible = true;ole.selection.find.forward =true;var rg=ole.selection.goto(true,0,0,"listyd");var tab=doc.Tables.Add(rg, 2,2) ;for(var i=1;i<=2;i++){for(var j=1;j<=2;j++){var rgcell=tab.Cell(i,j).Range;rgcell.InsertAfter(i+j);}}⽣成的表格嵌套在以前的表格中,很难看,如何能让⽣成的表格和外边的表格看上去是⼀个整体。

rgcell.InsertAfter(i+j);可以⽤insertBefore么。

也可以考虑⽤java语⾔做word模板。

③.⼩弟最近在做JSP页⾯内容导出到Word,但遇到了很多困难,望各位⼤侠急救需求:1.将JSP页⾯中的内容导出到Word⽂件中。

2.JSP页⾯中包含图⽚,图⽚的数据是从数据库中加载出来,实时⽣成的。

⼩弟在⽹上看过N个例⼦,也测试了,就是⽆法解决,问题如下:1.通过window.document.location.href='test.action'的链接⽅式,访问加⼀个JSP页⾯,⽂件头为:<%@ page contentType="application/msword;charset=gbk"%>当点击“导出”按钮时,可以⽣成Word⽂件,但是图⽚⽆法在Word中⽣成.2.直接在页⾯中加JS脚本:var oWD = new ActiveXObject("Word.Application");oWD.WindowState = 2;var oDC = oWD.Documents.Add("",0,1);var oRange =oDC.Range(0,1);var sel = document.body.createTextRange();sel.moveToElementText(PrintA);sel.select();sel.execCommand("Copy");oRange.Paste();oWD.Application.Visible = true;在我的电脑上可以导出Word(我的office版本是2007)⽂件,并且可以显⽰图⽚。

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

java操作word书签生成word模板(不用jar包)最近有个需求,在word模板文档上设置书签,然后从数据库中查询数据,填充到word 文档书签位置,刚拿到需求时,使劲在网上找资料。

幻想第三方jar包,帮我实现。

有Apatch 的POI,java2word,jcob等,一直让我无法实现。

POI操作word只能获取word中的书签,并不能进行操作.java2word可以实现,但是除了java2word.jar包以外,还要一个dll文件放在system32文件夹下,环境部署在linux服务器上,谁允许你放这样的文件,结果死心了.下面新建一个word2007文件告诉大家不用第三方技术怎么一一实现。

现在新建一个word,在请输入用户名处添加书签userName,请输入年龄处添加书签ageWord2007版本其实就是zip格式,将新建word后缀名改.zip,解压会发现,里面全是文件夹,打开word文件夹会有一个document.xml文件,在word所有内容,都在这xml文件中, <w:bookmarkStart w:id="0" w:name="userName"/><w:r><w:rPr><w:rFonts w:hint="eastAsia"/></w:rPr><w:t>请输入用户名</w:t></w:r><w:bookmarkEnd w:id="0"/>这是新建书签处的内容,细心的会发现,书签处内容在<w:bookmarkStart/> <w:bookmarkEnd w:id="0"/>标签之间,<w:bookmarkStart>标签中的w:id跟w:name标识书签的唯一,中间是书签处的内容,会不会可以这样呢,找到用dom或者sax解析这个xml 文档找到<w:bookmarkStart/>标签,然后找到<w:r>标签,再找到<w:r>标签里面的<w:t>标签内容,替换就Ok了呢。

一开始我就这样想的。

但是你会发现,<w:bookmarkStart></w:bookmarkStart>不是这样配套的,如果是这样配套的,那按照前面的说的直接解析找到<w:bookmarkStart>标签就OK了。

分析xml文件你会发现,其实<w:bookmarkStart w:id="0" w:name="userName"/>标签跟<w:r>标签是同级的,只是结束方式不同而已,所以算是兄弟节点,可以不可以找到<w:bookmarkStart>的兄弟节点,也就是<w:r>标签,然后找到<w:t>标签,替换其文本。

其实w3c中Element对象中提供了获取兄弟节点的方法,getNextSibling()获取下一个兄弟节点。

按照分析的思路是可以实现的。

但是会不会有疑问,如果<w:bookmarkStar>的下一个兄弟节点会不会不是<w:r>标签呢,是的,如果书签处无内容,就会是这样的<w:bookmarkStart w:id="0" w:name="userName"/><w:bookmarkEnd w:id="0"/>这样可以直接在<w:bookmarkStart>后面直接添加<w:r>标签你多试几个文档你会发现,无论多复杂,只要节操还在。

都会是这个样子。

除非那种非常恶心的word。

这个还得看你的word模板而论.这样的思路是可以实现了,但是该怎么用java搞定呢,下面贴出代码publicstaticvoid modifyDocumentAndSave() throws IOException,ZipException, SAXException, ParserConfigurationException,TransformerException, TransformerConfigurationException {// 使用java.util打开文件File file=new File("D:test.docx");boolean exist=file.exists();boolean read=file.canRead();boolean write=file.canWrite();System.out.println(exist);System.out.println(read);System.out.println(write);ZipFile docxFile = new ZipFile(file);// 返回ZipEntry应用程序接口ZipEntry documentXML =docxFile.getEntry("word/document.xml");InputStream documentXMLIS =docxFile.getInputStream(documentXML);DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();Document doc =dbf.newDocumentBuilder().parse(documentXMLIS);// linkMan tel proCode companyName fundName fundCode sysProCodeMap<String, String> bookMarkMap = new HashMap<String, String>();bookMarkMap.put("userName", "张三");bookMarkMap.put("password", "888888");/*** 书签列表*/NodeList this_book_list =doc.getElementsByTagName("w:bookmarkStart");if (this_book_list.getLength() != 0) {for(int j = 0; j < this_book_list.getLength(); j++) {// 获取每个书签Element oldBookStart = (Element)this_book_list.item(j);// 书签名String bookMarkName =oldBookStart.getAttribute("w:name");// 书签名,跟需要替换的书签传入的map集合比较for (Map.Entry<String, String> entry : bookMarkMap.entrySet()) {// 书签处值开始Node wr = doc.createElement("w:r");Node wt = doc.createElement("w:t");Node wt_text =doc.createTextNode(entry.getValue());wt.appendChild(wt_text);wr.appendChild(wt);// 书签处值结束if (entry.getKey().equals(bookMarkName)) {Element node = (Element)oldBookStart.getNextSibling();// 获取兄弟节点w:r// 如果书签处无文字,则在书签处添加需要替换的内容,如果书签处存在描述文字,则替换内容,用w:rNodeList wtList =node.getElementsByTagName("w:t");// 获取w:r标签下的显示书签处内容标签w:tif (wtList.getLength() == 0) { // 如果不存在,即,书签处本来就无内容,则添加需要替换的内容oldBookStart.appendChild(wr);} else { // 如果书签处有内容,则直接替换内容Element wtNode = (Element)wtList.item(0);wtNode.setTextContent(entry.getValue());}}}}}Transformer t =TransformerFactory.newInstance().newTransformer();ByteArrayOutputStream baos = newByteArrayOutputStream();t.transform(new DOMSource(doc), newStreamResult(baos));ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream("D:\\response.docx"));Enumeration entriesIter = docxFile.entries();while (entriesIter.hasMoreElements()) {ZipEntry entry = (ZipEntry)entriesIter.nextElement();//如果是document.xml则修改,别的文件直接拷贝,不改变word 的样式if(entry.getName().equals("word/document.xml")) { byte[] data = baos.toByteArray();docxOutFile.putNextEntry(newZipEntry(entry.getName()));docxOutFile.write(data, 0, data.length);docxOutFile.closeEntry();} else {InputStream incoming =docxFile.getInputStream(entry);//此处设定值需慎重,如果设置小了,会破坏word文档,至于为什么会破坏,自己去思考byte[] data = newbyte[1024 * 512]; int readCount = incoming.read(data, 0, (int) entry.getSize());docxOutFile.putNextEntry(newZipEntry(entry.getName()));docxOutFile.write(data, 0, readCount);docxOutFile.closeEntry();}}docxOutFile.close();}。

相关文档
最新文档