草庐IT

java用模板生成word(docx)文档(含动态表格)

奋豆来袭 2023-09-03 原文

生成word思路

用WPS或者office编辑好word的样式,然后另存为word xml文档,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板并输出Docx。

编辑好需要使用的word文档

1、把需要注入的信息换成变量名称,比如几年几月用${d1}表示,全部替换后的格式如下图所示

 对于表头的话最好设置成每页都自动生成表头

2、替换完成后另存为word xml格式的文档,如下图

 3、使用文本编辑器打开

4、xml格式化

https://c.runoob.com/front-end/710/

 5、选定表格的动态生成范围,添加 list 标签,记得保存

<#list TestList as item>

</#list>

 6、把改好的XML文件存放到项目的resources文件夹下,(我这里模板比较多,就自己建了一个word文件夹)

 7,导入依赖

<!-- 导出word -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/e-iceblue/spire.doc.free -->
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc.free</artifactId>
    <version>2.7.3</version>
</dependency>

 spire.doc.free这个依赖要在maven的setting配置加个仓库

      <repository>
      <id>e-iceblue</id>
      <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
      </repository>

 8,编写代码

control类

@GetMapping("/word02")
public void getWord02() throws Exception {
    //市级开卡数据
    ArrayList<HashMap<String, String>> list = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        HashMap<String, String> map = new HashMap<>();
        int a = i + 1;
        String s = Integer.toString(a);
        map.put("t1", s);
        map.put("t2", "666666");
        map.put("t3", "6666");
        map.put("t4", "66");
        map.put("t5", "6666");
        map.put("t6", "6666");
        map.put("t7", "66666666");
        list.add(map);
    }
    Map<String, Object> params = new HashMap<>();
    params.put("d1", "10月");
    params.put("d2", "666666");
    params.put("p1", "6666");
    params.put("p2", "6666");
    params.put("p3", "222211");
    params.put("TestList", list);

    Integer templateFileNumber = 2;
    WordUtil.createWord(params,templateFileNumber);
}

导出word工具类

/**
     * 将数据导入word模板生成word
     *
     * @param params             数据
     * @param templateFileNumber 1-模板 2-模板 3- 模板
     * @return docx临时文件的全路径
     * @throws IOException
     */
    private static String createWord(Map<String, Object> params, Integer templateFileNumber) throws IOException {
        String templateFile = null;
        //指定模板
        if (templateFileNumber == 1) {
            templateFile = "啊啊啊.xml";
        }
        if (templateFileNumber == 2) {
            templateFile = "哦哦哦.xml";
        }
        if (templateFileNumber == 3) {
            templateFile = "嗯嗯嗯.xml";
        }
        File file = null, templateFile1 = null;
        FileOutputStream fileOutputStream = null;
        Writer out = null;
        InputStream inputStream = null;
        try {
            //指定模板存放位置
            ClassPathResource tempFileResource = new ClassPathResource("word/" + templateFile);
            //创建临时文件
            file = File.createTempFile(templateFile, ".docx");
            //得到临时文件全路径  ,作为word生成的输出全路径使用
            String outputDir = file.getAbsolutePath();
            log.info("创建临时文件的路径为:{}", outputDir);

            //创建模板临时文件
            templateFile1 = File.createTempFile(templateFile, ".xml");
            fileOutputStream = new FileOutputStream(templateFile1);
            inputStream = tempFileResource.getInputStream();
            IOUtils.copy(inputStream, fileOutputStream);
            //得到临时模板文件全路径
            String templateFilePath = templateFile1.getAbsolutePath();
            log.info("创建临时文件的路径为:{}", templateFilePath);

//           new ClassPathResource("aaa").getInputStream().close();
            // 设置FreeMarker的版本和编码格式
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            // 设置FreeMarker生成Word文档所需要的模板的路径
            configuration.setDirectoryForTemplateLoading(templateFile1.getParentFile());
            // 设置FreeMarker生成Word文档所需要的模板
            Template t = configuration.getTemplate(templateFile1.getName(), "UTF-8");

            // 创建一个Word文档的输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputDir)), "UTF-8"));
            //FreeMarker使用Word模板和数据生成Word文档
            t.process(params, out); //将填充数据填入模板文件并输出到目标文件
        } catch (Exception e) {
            log.error("word生成报错,错误信息{}", e.getMessage());
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (templateFile1 != null) {
                templateFile1.delete();
            }
        }
        return file == null ? null : file.getAbsolutePath();
    }

最终会得到docx文件!!!!

有关java用模板生成word(docx)文档(含动态表格)的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  3. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  4. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  5. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby-on-rails - Ruby on Rails - 为文本区域和图片生成列 - 2

    我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  10. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

随机推荐