使用FreeMarker导出复杂的Word(具体实现)

来源:互联网 发布:怎么查看图片 html源码 编辑:程序博客网 时间:2024/06/18 10:41

(1)使用freemarker,首先在pom.xml里添加meaven依赖,如下图:

(2)建立一个Word文档,在这里我使用model.doc文件,在需要替换的地方使用”${XXX}”,PS:需要注意的是:书写”${XXX}”的时候,必须从左至右一个个书写,尤其是不能使用键盘上的上下左右的按键,不然生成的model.xml中会换行,导致生成word模板失败。
(3)新建一个类,这里我使用DoWordService

public DoWordService() {        configuration = new Configuration();        configuration.setDefaultEncoding("utf-8");    }public void createDoc(){Map dataMap = new HashMap();dataMap.put(String,String);//这里放入需要替换掉key,value// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,        // 这里我们的模板是放在E盘temps文件夹下面        configuration.setDirectoryForTemplateLoading(new File("E:/temps/"));        Template t ;        // test.ftl为要装载的模板        t = configuration.getTemplate("model.ftl");        t.setEncoding("utf-8");        // 输出文档路径及名称        File outFile = new File("E:/temps/models.doc");        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));        t.process(dataMap, out);        out.flush();        out.close();}//这里做模板xml(或者ftl文件)的字符替换,因为数据中不能使用尖括号和&等,需要在Java中替换成对应的转义字符换行符号使用<w:br />public String change(String str){        str =str.replaceAll("&nbsp;"," ");        str = str.replaceAll("<p>", "");        str = str.replaceAll("</p>", "&br&");        str = str.replaceAll(">", "&gt;");        str = str.replaceAll("<", "&lt;");        str = str.replaceAll("%", "");        str = str.replaceAll("&br&", "<w:br />");        return  str;    }  //这里获取图片的路径,imagesPath为文件的绝对路径(在controller中使用request.getSession.getServlet.Context().getRealPath())    private String getImageStr(String imagesPath,String images) {        String imgFile = imagesPath+images;        InputStream in;        byte[] data = null;        try {            in = new FileInputStream(imgFile);            data = new byte[in.available()];            in.read(data);            in.close();        } catch (IOException e) {            e.printStackTrace();        }        BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);    }

(4)将图片文件放在对应的包下
这里写图片描述
(5)操作流程:先新建一个model.doc(模板),然后另存为model.xml文件,将后缀名改为.ftl文件,由于ftl文件不能读取图片,编辑model.ftl文件,将乱码替换为例如${image},然后在Java里具体修改(见第三点)

2 0
原创粉丝点击