springboot结合Freemarker模板生成docx格式的word文档(附代码)

首先参考的是这篇文章:

java利用Freemarker模板生成docx格式的word文档(全过程) - 旁光 - 博客园参考:https://my.oschina.net/u/3737136/blog/2958421?tdsourcetag=s_pcqq_aiomsg 具体思路 1.创建一个docx文档模板,其中的英文https://www.cnblogs.com/ssyh/p/12494626.html我这次是通过Freemarker模板生成一个申请表,内容如下:

 1.先使用word把这个模板编写好,这要注意后缀为.docx

2.将这个文件的后缀改为.zip,然后解压在word目录下找到document.xml如下:

 3.将他复制到idea中格式化代码(内容非常多,格式化后好找)后修改,把name改为${name},其他也是一样:

 

 4.pom中导入依赖:

<dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>

5.编写工具类FreeMarkUtils:

public class FreeMarkUtils {
    private static Logger logger = LoggerFactory.getLogger(FreeMarkUtils.class);

    public static Configuration getConfiguration(){
        //创建配置实例
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        //设置编码
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(FreeMarkUtils.class, "/templates");//换成自己对应的目录
        return configuration;
    }

    /**
     * 获取模板字符串输入流
     * @param dataMap   参数
     * @param templateName  模板名称
     * @return
     */
    public static ByteArrayInputStream getFreemarkerContentInputStream(Map dataMap, String templateName) {
        ByteArrayInputStream in = null;
        try {
            //获取模板
            Template template = getConfiguration().getTemplate(templateName);
            StringWriter swriter = new StringWriter();
            //生成文件
            template.process(dataMap, swriter);
            in = new ByteArrayInputStream(swriter.toString().getBytes("utf-8"));//这里一定要设置utf-8编码 否则导出的word中中文会是乱码
        } catch (Exception e) {
            logger.error("模板生成错误!");
        }
        return in;
    }
}

6.编写controller:FreemarkerController

@Controller
public class FreemarkerController {

    @Resource
    ShenqingDao shenqingDao;

    private static String document= "document.xml";

    /**
     * 导出申请表
     *
     * @param id
     * @return
     */
    @RequestMapping("manage/dc")
    @ResponseBody
    public ResultUtil dc(Integer id) {
        try {
            Shenqing shenqing = shenqingDao.queryById(id);
            System.out.println(shenqing);
            Map dataMap=new HashMap();
            dataMap.put("xueyuan", shenqing.getXueyuan());
            dataMap.put("zhuanye", shenqing.getZhuanye());
            dataMap.put("classname", shenqing.getClassname());
            dataMap.put("name", shenqing.getName());
            dataMap.put("gender", shenqing.getGender());
            dataMap.put("birthday", shenqing.getBirthday());
            dataMap.put("jiguan", shenqing.getJiguan());
            dataMap.put("idnum", shenqing.getIdnum());
            dataMap.put("familynum", shenqing.getFamilynum());
            dataMap.put("tel", shenqing.getTel());
            dataMap.put("addr", shenqing.getAddr());
            dataMap.put("youbian", shenqing.getYoubian());
            dataMap.put("familytel", shenqing.getFamilytel());
            dataMap.put("Intro", shenqing.getIntro());
            dataMap.put("yyijian", shenqing.getYyijian());
            dataMap.put("yijian", shenqing.getXyijian());


            //指定输出docx路径
            File outFile = new File("C:\\Users\\dyb\\IdeaProjects\\zizhu\\src\\main\\resources\\templates\\家庭经济困难学生认定申请表.docx") ;
            createDocx(dataMap,new FileOutputStream(outFile));

            return ResultUtil.ok("导出申请表成功");
        } catch (Exception e) {
            return ResultUtil.error("导出申请表,稍后再试!");
        }
    }



    //outputStream 输出流可以自己定义 浏览器或者文件输出流
    public static void createDocx(Map dataMap, OutputStream outputStream) {
        ZipOutputStream zipout = null;
        try {
            /*//图片配置文件模板
            ByteArrayInputStream documentXmlRelsInput = FreeMarkUtils.getFreemarkerContentInputStream(dataMap, documentXmlRels);*/

            //内容模板
            ByteArrayInputStream documentInput = FreeMarkUtils.getFreemarkerContentInputStream(dataMap, document);
            //最初设计的模板
            //File docxFile = new File(WordUtils.class.getClassLoader().getResource(template).getPath());
            File docxFile = new File("C:\\Users\\dyb\\IdeaProjects\\zizhu\\src\\main\\resources\\templates\\家庭经济困难学生认定申请表(模版).zip");//换成自己的zip路径
            if (!docxFile.exists()) {
                System.out.println(111111);
                docxFile.createNewFile();
            }
            ZipFile zipFile = new ZipFile(docxFile);
            Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
            zipout = new ZipOutputStream(outputStream);
            //开始覆盖文档------------------
            int len = -1;
            byte[] buffer = new byte[1024];
            while (zipEntrys.hasMoreElements()) {
                ZipEntry next = zipEntrys.nextElement();
                InputStream is = zipFile.getInputStream(next);
                if (next.toString().indexOf("media") < 0) {
                    zipout.putNextEntry(new ZipEntry(next.getName()));
                    if ("word/document.xml".equals(next.getName())) {//如果是word/document.xml由我们输入
                        if (documentInput != null) {
                            while ((len = documentInput.read(buffer)) != -1) {
                                zipout.write(buffer, 0, len);
                            }
                            documentInput.close();
                        }
                    } else {
                        while ((len = is.read(buffer)) != -1) {
                            zipout.write(buffer, 0, len);
                        }
                        is.close();
                    }
                }
            }

        } catch (Exception e) {
            System.out.println("word导出失败:"+e.getStackTrace());
            //logger.error();
        }finally {
            if(zipout!=null){
                try {
                    zipout.close();
                } catch (IOException e) {
                    System.out.println("io异常");

                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    System.out.println("io异常");
                }
            }
        }
    }
}

7.前端:

<a class="layui-btn layui-btn-warm  layui-btn-xs" lay-event="dc">导出申请表</a>

 
layer.confirm('确定导出?', function (index) {
                $.ajax({
                    url: ctx + '/manage/dc?id=' + data.id,
                    type: "get",
                    success: function (d) {
                        if (d.code == 0) {
                            layer.msg(d.msg, {icon: 1});
                            table.reload('userinfoList', {})
                        } else {
                            layer.msg("操作失败,请重试", {icon: 5});
                        }
                    }
                })
                layer.close(index);
            });

项目结构:

 最后的效果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值