栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA 根据模板生成doc文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA 根据模板生成doc文件

JAVA 根据模板生成doc文件 需求

根据模板生成对应的doc文档,文档内容动态填充。

实现

1.将doc模板转换为ftl文件,放入项目中
1.1 首先将模板另存为xml文件
1.2 更改xml文件后缀为ftl,即可把doc转为ftl.
2.代码实现
2.1 首先根据自身需求获取文档动态内容的数据,由于业务不同,这里不做过多阐述,我这里数据的返回类型为MAP.
2.2 通过调用方法,生成文档并通过浏览器下载

public static void WordExport(Map dataMap) throws IOException {
    HttpServletResponse response = ServletActionContext.getResponse();
    String eventId = "测试文档-" + dataMap.get("tasknum");

    //Configuration用于读取ftl文件
    Configuration configuration = new Configuration();
    configuration.setDefaultEncoding("utf-8");
    //指定路径
    String templateFolder = NotTrueWorkOrderDocAction.class.getClassLoader().getResource("../../").getPath() + "templates/";
    configuration.setDirectoryForTemplateLoading(new File(templateFolder));
    // 输出文档路径及名称
    File outFile = new File(templateFolder + eventId + ".doc");

    //以 utf-8 的编码读取ftl文件
    Template t = null;
    //自己生成的ftl文件
    t = configuration.getTemplate("nottrueworkorder.ftl", "utf-8");
    Writer out = null;
    out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
    try {
        t.process(dataMap, out);
    } catch (TemplateException e) {
        e.printStackTrace();
    }
    out.close();

    InputStream fin = null;
    ServletOutputStream download = null;
    try {
        fin = new FileInputStream(outFile);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        // 设置浏览器以下载的方式处理该文件名
        String FileName = eventId + ".doc";
        response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(FileName, "UTF-8"))));
        download = response.getOutputStream();
        IOUtils.copy(fin, download);
        download.flush();
        fin.close();
    } finally {
        if (fin != null) {
            fin.close();
            if (download != null) {
                download.close();
            }
            if (outFile != null) {
                outFile.delete(); // 删除临时文件
            }
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/462232.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号