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

java生成word,freemarker实现

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

java生成word,freemarker实现

1.用word设置好你需要生成的word模板

2.将word文档设置成.xml格式(注意"${}"符号是否按照规范显示成xml文档)

3.话不多少上代码

        //xml文件放至位置
        String xmlPath = "G:/report/upload/test.xml";
        //word生成位置
        String uploadPath="G:/report/upload/";
        //word生成名字
        String targetName="word.doc";
        //获得xml文件夹路径
        String templatePath=xmlPath.substring(0,xmlPath.lastIndexOf("/")); 
        //获得xml名字
        String templateName=xmlPath.substring(xmlPath.lastIndexOf("/") + 1, xmlPath.length());
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            //判断生成位置是否存在,不存在则创建
            File file = new File(uploadPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 加载模板数据(从文件路径中获取文件,其他方式)
            configuration.setDirectoryForTemplateLoading(new File(templatePath));
            Template template = configuration.getTemplate(templateName);
            File outFile = new File(uploadPath + File.separator + targetName);
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "UTF-8"));

            Map dataMap =new HashMap<>();
            User user=new User();
            user.setName("陈惊");
            user.setAge(25);
            user.setSex("男");
            String text="互相学习过程";
            dataMap.put("table",user);
            dataMap.put("text",text);
            //生成文件
            template.process(dataMap, out);
            //关闭资源
            out.flush();
            out.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

4.效果如下

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/821047.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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