html转Excel更神奇的导出
这个是一个MM提出的需求,需求原因是,她要导出一个比较复杂的Excel,无论用模板还是注解都比较难实现,所以她想到了这个方案,然后就实现了如下的方法,我的使用方法如下 自己搞个html,然后用模板引擎,beetl,freemark等生成html,然后调用autopoi提供的方法转换成Excel,因为html的标签以及规则大家比Excel要熟悉的多,更容易编写复杂的table,然后autopoi转换成Excel再导出,麻烦了点,但是可以处理一些特定的情况,也同样生成两个版本的Excel都支持 使用demo
@Test
public void htmlToExcelByStr() throws Exception {
StringBuilder html = new StringBuilder();
Scanner s = new Scanner(getClass().getResourceAsStream("/html/sample.html"), "utf-8");
while (s.hasNext()) {
html.append(s.nextLine());
}
s.close();
Workbook workbook = ExcelXorHtmlUtil.htmlToExcel(html.toString(), ExcelType.XSSF);
File savefile = new File("D:\\home\\lemur");
if (!savefile.exists()) {
savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream("D:\\home\\lemur\\htmlToExcelByStr.xlsx");
workbook.write(fos);
fos.close();
workbook = ExcelXorHtmlUtil.htmlToExcel(html.toString(), ExcelType.HSSF);
fos = new FileOutputStream("D:\\home\\lemur\\htmlToExcelByStr.xls");
workbook.write(fos);
fos.close();
}
@Test
public void htmlToExcelByIs() throws Exception {
Workbook workbook = ExcelXorHtmlUtil.htmlToExcel(getClass().getResourceAsStream("/html/sample.html"), ExcelType.XSSF);
File savefile = new File("D:\\home\\lemur");
if (!savefile.exists()) {
savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream("D:\\home\\lemur\\htmlToExcelByIs.xlsx");
workbook.write(fos);
fos.close();
workbook = ExcelXorHtmlUtil.htmlToExcel(getClass().getResourceAsStream("/html/sample.html"), ExcelType.HSSF);
fos = new FileOutputStream("D:\\home\\lemur\\htmlToExcelByIs.xls");
workbook.write(fos);
fos.close();
}
提供了流或者字符串的入参,内部都多了缓存,多次生成不会重复解析