springboot~aspose *** 作word模板实现导出功能

springboot~aspose *** 作word模板实现导出功能,第1张

事情是这样的,系统有这样一个需求,有一些单子供客户下载打印,做为凭证,而这些单子一般属于word格式的,里面的排版非常固定,只是上面的内容不同,这就属于word模板的范畴了,目前比较不好的 *** 作word的组件就是aspose了,下面我来说一下它的使用方法。

word模板

主要使用了word里的域,然后选择“邮件合并”,在“域名”处输入你的word变量名,然后在java代码里为这个变量赋值就可以了

添加组件引用

把组件放到resource/lib目录下

        
            com.bdyh.common
            common
            0.0.1
            system
            ${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar
        
代码生成

aspose组件存在授权问题,没有授权的会有水印出现

  private static InputStream license;
  private static InputStream fileInput;
 public static void generateApproveForm(HttpServletResponse response,
                                         List counterpartDetails) {
    // 验证License
    if (!getLicense("templates/companyLawyerApprove.docx")) {
      return;
    }
    try {
      long old = System.currentTimeMillis();
      Document doc = new Document(fileInput);
      //主要调用aspose.words的邮件合并接口MailMerge
      //3.1 填充单个文本域
      String[] Flds = new String[]{"Title", "Name", "URL", "Note"}; //文本域
      Object[] Vals = new Object[]{"标题", "测试",  "http://test.com", word模板导出"}; //值
      doc.getMailMerge().execute(Flds, Vals); //调用接口
      response.setHeader("Content-Disposition", "attachment; filename=审批单.pdf");
      response.setContentType("application/octet-stream;charset=UTF-8");

      OutputStream output = response.getOutputStream();
      doc.save(output, SaveFormat.PDF);

      output.flush();
      output.close();
}

 public static boolean getLicense(String templateName) {
    boolean result = false;
    try {
      license = new ClassPathResource("lib/license.xml").getInputStream();
      fileInput = new ClassPathResource(templateName).getInputStream();

      License aposeLic = new License();
      aposeLic.setLicense(license);
      result = true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

以上模板是最简单的文本域的,如果有兴趣还可以把表格域也放上去,实现列表的输出等。

愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系,可以微信搜索539413949获取,最后祝大家都能拿到自己心仪的offer

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/729396.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存