java调用word模板.docx

上传人:b****6 文档编号:8904611 上传时间:2023-05-15 格式:DOCX 页数:9 大小:18.29KB
下载 相关 举报
java调用word模板.docx_第1页
第1页 / 共9页
java调用word模板.docx_第2页
第2页 / 共9页
java调用word模板.docx_第3页
第3页 / 共9页
java调用word模板.docx_第4页
第4页 / 共9页
java调用word模板.docx_第5页
第5页 / 共9页
java调用word模板.docx_第6页
第6页 / 共9页
java调用word模板.docx_第7页
第7页 / 共9页
java调用word模板.docx_第8页
第8页 / 共9页
java调用word模板.docx_第9页
第9页 / 共9页
亲,该文档总共9页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

java调用word模板.docx

《java调用word模板.docx》由会员分享,可在线阅读,更多相关《java调用word模板.docx(9页珍藏版)》请在冰点文库上搜索。

java调用word模板.docx

java调用word模板

竭诚为您提供优质文档/双击可除

java调用word模板

  篇一:

java生成word文件并下载

  importjava.io.bufferedinputstream;

  importjava.io.bufferedoutputstream;

  importjava.io.bufferedwriter;

  importjava.io.File;

  importjava.io.Fileinputstream;

  importjava.io.Fileoutputstream;

  importjava.io.ioexception;

  importjava.io.inputstream;

  importjava.io.outputstream;

  importjava.io.outputstreamwriter;

  importjava.io.writer;

  .uRlencoder;

  importjava.util.map;

  importjavax.servlet.http.httpservletResponse;

  importorg.apache.log4j.logger;

  importfreemarker.template.configuration;

  importfreemarker.template.template;

  /**

  *@desc:

word操作工具类

  */

  publicclasswordutil{

  privatestaticloggerlog=logger.getlogger(wordutil.class);

  /**

  *@desc:

生成word文件

  *@paramdatamapword中需要展示的动态数据,用map集合来保存

  *@paramtemplatenameword模板名称,例如:

test.ftl

  *@paramfilepath文件生成的目标路径,例如:

d:

/wordFile/

  *@paramfilename生成的文件名称,例如:

test.doc

  */

  publicstaticvoidcreateword(mapdatamap,stringtemplatename,stringfilepath,stringfilename){

  try{

  //创建配置实例

  configurationconfiguration=newconfiguration();

  //设置编码

  configuration.setdefaultencoding("utF-8");

  //ftl模板文件

  Filefile=newFile(filepath);

  configuration.setdirectoryFortemplateloading(file);

  //获取模板

  templatetemplate=configuration.gettemplate(templatename);

  //输出文件

  FileoutFile=newFile(filepath+File.separator+filename);

  //如果输出目标文件夹不存在,则创建

  if(!

outFile.getparentFile().exists()){

  outFile.getparentFile().mkdirs();

  }

  //将模板和数据模型合并生成文件

  writerout=newbufferedwriter(newoutputstreamwriter(newFileoutputstream(outFile),"utF-8"));

  //生成文件

  template.process(datamap,out);

  //关闭流

  out.flush();

  out.close();

  }catch(exceptione){

  log.error("生成word文档(wordutil)出错:

【msg:

"+e.getmessage()+"】,文件名:

"+filename);

  e.printstacktrace();

  }

  }

  /**

  *文件下载

  *@parampath文件路径全路径,包含文件名

  *@paramresponse

  *@return

  */

  publicstatichttpservletResponsedownFile(stringpath,httpservletResponseresponse){try{

  //path是指欲下载的文件的路径。

  Filefile=newFile(path);

  //取得文件名。

  stringfilename=file.getname();

  //以流的形式下载文件。

  inputstreamfis=newbufferedinputstream(newFileinputstream(file));

  byte[]buffer=newbyte[fis.available()];

  }fis.read(buffer);fis.close();//清空responseresponse.reset();//设置response的headerstringfilename=uRlencoder.encode(filename,"utF-8");if(filename.length()>150){//解决ie6.0bugfilename=newstring(filename.getbytes("gbk"),"iso-8859-1");}response.addheader("content-disposition","attachment;filename="+filename);response.addheader("content-length",""+file.length());outputstreamtoclient=newbufferedoutputstream(r  

esponse.getoutputstream());response.setcontenttype("application/octet-stream");toclient.write(buffer);toclient.flush();toclient.close();file.delete();}catch(ioexceptione){log.error("下载文档(wordutil)出错:

【msg:

"+e.getmessage()+"】");e.printstacktrace();}returnresponse;}

  篇二:

jaVa生成word文档代码加说明

  importjava.io.bytearrayoutputstream;

  importjava.io.File;

  importjava.io.Fileinputstream;

  importjava.io.FilenotFoundexception;

  importjava.io.Fileoutputstream;

  importjava.io.ioexception;

  importjava.io.outputstream;

  importjava.util.iterator;

  importjava.util.map;

  importjavax.servlet.http.httpservletResponse;

  importorg.apache.poi.hwpf.hwpFdocument;

  importorg.apache.poi.hwpf.model.Fieldsdocumentpart;

  importorg.apache.poi.hwpf.usermodel.Field;

  importorg.apache.poi.hwpf.usermodel.Fields;

  importorg.apache.poi.hwpf.usermodel.Range;

  importorg.apache.poi.hwpf.usermodel.table;

  importorg.apache.poi.hwpf.usermodel.tableiterator;

  importorg.apache.poi.hwpf.usermodel.tableRow;

  publicclasswordutil{

  publicstaticvoidreadwriteword(stringfilepath,stringdownpath,mapmap,int[]num,stringdownFilename){//读取word模板Fileinputstreamin=null;try{}hwpFdocumenthdt=null;try{}Fieldsfields=hdt.getFields();iteratorit=fields.getFields(Fieldsdocumentpart.main).iterator();while(it.hasnext()){system.out.println(it.next().gettype());}hdt=newhwpFdocument(in);e1.printstacktrace();}catch(ioexceptione1){in=newFileinputstream(newFile(filepath));e1.printstacktrace();}catch(FilenotFoundexceptione1){

  //读取word表格内容try{Rangerange=hdt.getRange();//得到文档的读取范围tableiteratorit2=newtableiterator(range);//迭代文档中的表格inttabcount=0;while(it2.hasnext()){//system.out.println("第几个表格"+tabcount);//system.out.println(num[tabcount]+"行");tabletb2=(table)it2.next();//迭代行,默认从0开始for(inti=0;ientry:

map.entryset()){}range.replacetext("$"+entry.getkey().trim()+"$",entry.getValue());

  //system.out.println("替换后------------:

  "+range.text().trim());

  }catch(exceptione){}//e.printstacktrace();

  system.out.println("--------------------------------------------------------------------------------------");

  bytearrayoutputstreamostream=newbytearrayoutputstream();stringfilename=downFilename;filename+=".doc";stringpathandname=downpath+filename;Filefile=newFile(pathandname);if(file.canRead()){}Fileoutputstreamout=null;file.delete();

  }}try{}//输出字节流try{}try{}try{}ostream.close();e.printstacktrace();}catch(ioexceptione){out.close();e.printstacktrace();}catch(ioexceptione){out.write(ostream.tobytearray());e.printstacktrace();}catch(ioexceptione){hdt.write(ostream);e.printstacktrace();}catch(ioexceptione){out=newFileoutputstream(pathandname,true);e.printstacktrace();}catch(FilenotFoundexceptione){/***实现对word读取和修改操作(输出文件流下载方式)*@paramresponse响应,设置生成的文件类型,文件头编码方式和文件名,以及输出*@paramfilepathword模板路径和名称*@parammap待填充的数据,从数据库读取*/publicstaticvoidreadwriteword(httpservletResponseresponse,stringfilepath,mapmap){//读取word模板文件//stringfiledir=new

  File(base.getFile(),"//../doc/").getcanonicalpath();

  //Fileinputstreamin=newFileinputstream(newFileinputstreamin;hwpFdocumenthdt=null;File(filedir+"/laokboke.doc"));

  }}}Fieldsfields=hdt.getFields();iteratorit=fields.getFields(Fieldsdocumentpart.main)}//替换读取到的word模板内容的指定字段Rangerange=hdt.getRange();for(map.entryentry:

map.entryset()){}//输出word内容文件流,提供下载response.reset();response.setcontenttype("application/x-msdownload");stringfilename=""+system.currenttimemillis()+".doc";response.addheader("content-disposition","attachment;+filename);range.replacetext("$"+entry.getkey()+"$",.iterator();while(it.hasnext()){system.out.println(it.next().gettype());in=newFileinputstream(newFile(filepath));hdt=newhwpFdocument(in);e1.printstacktrace();}catch(exceptione1){entry.getValue());filename="bytearrayoutputstreamostream=newbytearrayoutputstream();outputstreamservletos=null;try{}servletos=response.getoutputstream();hdt.write(ostream);servletos.write(ostream.tobytearray());servletos.flush();servletos.close();e.printstacktrace();}catch(exceptione){

  注:

以上代码需要poi包,可以下载。

  篇三:

java完美生成word的解决方案

  poi读word文档还行,写文档实在不敢恭维,复杂的样式很难控制不提,想象一下一个20多页,嵌套很多表格和图像的word文档靠poi来写代码输出,对程序员来说比去山西挖煤还惨,况且文档格式还经常变化。

  itext操作excel还行。

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

  直接通过jsp输出样式基本不达标,而且要打印出来就更是惨不忍睹。

  word从20xx开始支持xml格式,用xml还做就很简单了。

  大致的思路是先用office20xx或者20xx编辑好word的样式,然后另存为xml,将xml翻译为Freemarker模板,最后用java来解析Freemarker模板并输出doc。

经测试这样方式生成的word文档完全符合office标准,样式、内容控制非常便利,打印也不会变形,生成的文档和office中编辑文档完全一样。

  看看实际效果:

  首先用office【版本要20xx以上,以下的不支持xml格式】编辑文档的样式,图中红线的部分就是我要输出的部分:

  将编辑好的文档另存为xml

  再用Firstobjectfreexmleditor【Firstobjectfreexmleditor的使用见这里】将xml中我们需要填数据的地方打上Freemarker标记【Freemarker的语法见这里】

  最后生成的文档样式

  主要程序代码:

  viewsourceprint01packagecom.havenliu.document;

  02

  03importjava.io.bufferedwriter;

  04importjava.io.File;

  05importjava.io.FilenotFoundexception;

  06importjava.io.Fileoutputstream;

  07importjava.io.ioexception;

  08importjava.io.outputstreamwriter;

  09importjava.io.writer;

  10importjava.util.arraylist;

  11importjava.util.hashmap;

  12importjava.util.list;

  13importjava.util.map;

  14

  15importfreemarker.template.configuration;

  16importfreemarker.template.template;

  17importfreemarker.template.templateexception;

  18

  19publicclassdocumenthandler{

  20privateconfigurationconfiguration=null;

  21

  22publicdocumenthandler(){

  23configuration=newconfiguration();

  24configuration.setdefaultencoding("utf-8");

  25}

  26

  27publicvoidcreatedoc(){

  28//要填入模本的数据文件

  29mapdatamap=newhashmap();

  30getdata(datamap);

  31//设置模本装置方法和路径,Freemarker支持多种模板装载方法。

可以重servlet,classpath,数据库装载,

  32//这里我们的模板是放在com.havenliu.document.template包下面

  33configuration.setclassFortemplateloading(this.getclass(),

  "/com/havenliu/document/template");

  34templatet=null;

  35try{

  36//test.ftl为要装载的模板

  37t=configuration.gettemplate("test.ftl");

  38}catch(ioexceptione){

  39e.printstacktrace();

  40}

  41//输出文档路径及名称

  42FileoutFile=newFile("d:

/temp/outFile.doc");

  43writerout=null;

  44try{

  45out=newbufferedwriter(new

  Fileoutputstream(outFile)));

  46}catch(FilenotFoundexceptione1){

  47e1.printstacktrace();

  48}

  49

  50try{

  51t.process(datamap,out);

  52}catch(templateexceptione){

  53e.printstacktrace();

  54}catch(ioexceptione){

  55e.printstacktrace();

  56}

  57}outputstreamwriter(new

  58

  59/**

  60*注意datamap里存放的数据key值要与模板中的参数相对应

  61*@paramdatamap

  62*/

  63privatevoidgetdata(mapdatamap)

  64{

  65datamap.put("author","张三");

  66datamap.put("remark","这是测试备注信息");

  67list

  68_table1=newarraylist

  69();

  70

  71table1t1=newtable1();

  72t1.setdate("20xx-10-1");

  73t1.settext("制定10月开发计划内容。

");

  74_table1.add(t1);

  75

  76table1t2=newtable1();

  77t2.setdate("20xx-10-2");

  78t2.settext("开会讨论开发计划");

  79_table1.add(t2);

  80

  81datamap.put("table1",_table1);

  82

  83list

  84_table2=newarraylist

  85();

  86for(inti=0;i  87{

  88table2_t2=newtable2();

  89_t2.setdetail("测试开发计划"+i);

  90_t2.setperson("张三——"+i);

  91_t2.setbegindate("20xx-10-1");

  92_t2.setFinishdate("20xx-10-31");

  93_t2.setRemark("备注信息");

  94_table2.add(_t2);

  95}

  96datamap.put("table2",_table2);

  97}

  98}

  转自/java/514.html

  --------------------------------------------------------------------------------

  开发一个word的代码高亮插件

  在用word写技术文档的时候,免不了要在文档中插入一些源代码。

为了使插入进来的源代码更可读,就需要

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 初中教育 > 语文

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2