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

java导出文档

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

java导出文档

导出文档
  • 第一步就是将World文档里面需要从数据库填充的部分用占位符替换
  • 第二步:就是将此文档保存为Xml格式
  • 第四步:将其放在resource目录下,并选中此文件,右键点击properties属性,将其编码格式设置为Utf-8(防止生成之后乱码)
  • 第四步:将此文件后缀名改为ftl
导入依赖

    org.freemarker
    freemarker
    2.3.23

编写配置
word:
    ftlInheritorName: application.ftl #导出word申请表的模板名
    wordInheritorName: 申报文档 #导出申请表word的名字
    templatePath:  E:warehouse文化图书馆whtsgsrcmainresourcesftl #模板所在位置
    wordProjectName: 申报书 #导出非遗申报书word的名字
    ftlDeclarationName: declaration.ftl #导出word申报书的模板名
代码层

@Autowired
private Environment env;

@Override
public void derive(HttpServletRequest request, HttpServletResponse response,String id) throws Exception {
    //根据id查询数据
    HeritageProjectVo heritageProjectVo = getById(id);
    //存储需要替换的数据
    Map map = new HashMap<>();
    //基础数据
    map.put("proCode",HeritageProjectEnum.ProCode.getName(heritageProjectVo.getProCode()));
    map.put("category",HeritageProjectEnum.Category.getName(heritageProjectVo.getCategory()));
    map.put("proName", heritageProjectVo.getProName());
    map.put("recUnit", heritageProjectVo.getDirectorDept());
    map.put("declareArea", heritageProjectVo.getProAddress());
    map.put("involve", heritageProjectVo.getInvolve());
    map.put("proSituation", heritageProjectVo.getProIntro());
    map.put("basicComponents", heritageProjectVo.getHeritageInfo());
    map.put("distributionArea", heritageProjectVo.getRegion());
    map.put("historicalOrigin", heritageProjectVo.getHistory());
    map.put("inheritAncestry", heritageProjectVo.getInheritSpec());
    map.put("inheritGroup", heritageProjectVo.getInheritPeople());
    //getProperty()获取配制文中的件属性值
wordUtils.exportMillCertificateWord(request,response,map,env.getProperty("word.wordProjectName"),env.getProperty("word.ftlDeclarationName"),env.getProperty("word.templatePath"));
}
编写工具类
package com.sykj.why.util;

import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Service;

@Service
public class WordUtils {


    private static Configuration configuration = null;
    //TODO 线上需要将ftl文件地址更换
    // 这是word模板的存放位置
    private String templateFolder;


    private boolean connection(HttpServletRequest request, String templatePath) {
        try {
            if (templateFolder == null) {
                templateFolder = templatePath;
            }
            // Configuration 实例是存储 FreeMarker 应用级设置的核心部分。同时,它也处理创建和 缓存 预解析模板的工作。创建Configuration配置实例,			   Configuration.VERSION_2_3_0(FreeMarker 版本 2.3.0)
            //注意不管一个系统有多少独立的组件来使用 FreeMarker, 它们都会使用他们自己私有的 Configuration 实例。
            configuration = new Configuration(Configuration.VERSION_2_3_0);
            //设置模板文件存放的首选字符集
            configuration.setDefaultEncoding("utf-8");
            //指定模板文件的来源
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    
    public void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile, String templatePath) throws IOException {

        if (connection(request, templatePath) == false) {
            return;
        }
		
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(title, map, freemarkerTemplate);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = title + ".doc";
            //concat():将指定的字符串连接到该字符串的末尾
            //URLEncoder类包含一个encode(String s,String charcter)静态方法,它可以将普通字符串转换成application/x-www-form-urlencoded 			  MIME字符串
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

            out = response.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null) fin.close();
            if (out != null) out.close();
            if (file != null) file.delete(); // 删除临时文件
        }
    }

    
    private File createDoc(String name, Map dataMap, Template template) {
        File f = new File(name);
        Template t = template;
        try (
                // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
                Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");//创建一个使用给定字符集的OutputStreamWriter。 
        ) {
			//process方法将数据与模板进行绑定
            t.process(dataMap, w);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424995.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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