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

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

word模板

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

添加组件引用

把组件放到resource/lib目录下

        <dependency>
            <groupId>com.bdyh.common</groupId>
            <artifactId>common</artifactId>
            <version>0.0.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
        </dependency>

代码生成

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

  private static InputStream license;
  private static InputStream fileInput;
 public static void generateApproveForm(HttpServletResponse response,
                                         List<CompanyLawyerEducationAddDTO> 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;
  }

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

posted @ 2020-03-07 13:15  张占岭  阅读(2445)  评论(0编辑  收藏  举报