Java读取word模板并在模板相关位置插入数据和表格

来源:互联网 发布:金知元 知乎 编辑:程序博客网 时间:2024/05/22 06:05

这两天一直在实现这样一个功能,即从数据库及其他数据源中获取相关数据,填充到一定的word模板中,然后将该模板下载下来(主要就是为了以简单的方式让老师看到他想看的系统中不同功能不同位置地方的数据大哭

       最终这个功能是使用 freemarker实现的,真的很方便也很强大(也许是我孤陋寡闻了吐舌头

步骤:

首先创建要下载的模板,在需要填充数据的地方用${name}来代替。

如下图所示:

2、将doc文件另存为xml文件。直接另存为即可。

3、然后将xml文件重命名为ftl文件,我使用的是firstobject-XML-editor这个软件来编辑ftl文件。比如在需要插入表格的地方添加如下的代码:


为了让代码可读性变高,可以按F8进行代码的校验。

4.、模板准备工作完成,开始写代码

首先把要填充的数据封装好,使用的是Map容器进行封装的,如下图所示


得到的数据类似于下面


5、所有数据封装完毕后,开始将数据填充到模板中,调用下列的类及其create函数,create具体实现如下图所示:


public static File create(Map<?, ?> dataMap, String templateName,String filePath, String fileName) {System.out.println();File file = null;try {Version version = new Version("2.3.22");//创建配置实例Configuration configuration = new Configuration(version);//设置编码configuration.setDefaultEncoding("UTF-8");//ftl模板文件统一放至"/com/glwf/template/" 包下面configuration.setClassForTemplateLoading(WordUtils.class,"/com/glwf/template/"); //获取模板Template template = configuration.getTemplate(templateName);//输出文件File outFile = new File(filePath + File.separator + fileName); //如果输出目标文件夹不存在,则创建if (!outFile.getParentFile().exists()) {outFile.getParentFile().mkdirs();}//将模板和数据模型合并生成文件Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));//生成文件template.process(dataMap, out);//关闭流out.flush();out.close();file = outFile.getAbsoluteFile();} catch (TemplateException e) {log.error("TemplateException");} catch (TemplateNotFoundException e) {log.error("TemplateNotFoundException");} catch (MalformedTemplateNameException e) {log.error("MalformedTemplateNameException");} catch (ParseException e) {log.error("ParseException");} catch (IOException e) {log.error("IOException");}return file;}
6、文件生成,下载文件

if(file != null){/** * start down load the zip file * 开始下载  */System.out.println("开始下载。。。。。");HttpServletResponse response = this.getResponse();response.setContentType("application/x-download");response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes(), "ISO-8859-1"));OutputStream outp = null;FileInputStream in = null;outp = response.getOutputStream();in = new FileInputStream(file);byte[] b = new byte[1024];int i = 0;while ((i = in.read(b)) > 0) {outp.write(b, 0, i);}outp.close();log.info("down load success");file.delete();log.info("delete files success");}else{System.out.println("下载失败");log.error("zip file is not exist");}




原创粉丝点击