springboot~aspose操(cao)作word模(mo)板實(shi)現導出功能
事情(qing)是(shi)(shi)這(zhe)樣的(de),系統(tong)有(you)這(zhe)樣一(yi)個需(xu)求,有(you)一(yi)些單子(zi)供客戶下(xia)載打印,做為(wei)憑證,而這(zhe)些單子(zi)一(yi)般屬于(yu)word格式的(de),里(li)面的(de)排版非常固定,只是(shi)(shi)上面的(de)內容不同,這(zhe)就屬于(yu)word模(mo)板的(de)范疇了,目前比較(jiao)不好的(de)操作word的(de)組件就是(shi)(shi)aspose了,下(xia)面我來(lai)說一(yi)下(xia)它(ta)的(de)使(shi)用方法(fa)。
word模板
主要使用了(le)word里的(de)域(yu),然后選擇“郵(you)件(jian)合并”,在“域(yu)名”處(chu)輸入你的(de)word變量名,然后在java代(dai)碼里為這(zhe)個變量賦值就可以(yi)了(le)
添加組件引用
把組件(jian)放到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組件存(cun)在授權問題(ti),沒有(you)授權的會有(you)水(shui)印出(chu)現
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[]{"標題", "測試", "//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;
}
以(yi)(yi)上模板(ban)是最簡(jian)單的文本域的,如果(guo)有興趣還可以(yi)(yi)把表格域也放(fang)上去(qu),實現列表的輸出等。