生成excel模板的方法
需要提前编写好一个预置模板,其中重复的数据使用{.xxx}的格式包裹,总计用{xxx}的格式包裹。
通过下面的代码传入linkNames,可以生成多个sheet页。
@SneakyThrows
public static InputStream getTemplate(String templateName, List<String> linkNames,
String pathName) {
File directory = new File(pathName);
String reportPath;
InputStream is = null;
XSSFWorkbook workbook = null;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
//模板路径
String url = "/templates" + templateName + ".xlsx";
InputStream inputStream = new FileInputStream(url);
//原模板只有一个sheet,通过poi复制出需要的sheet个数的模板
workbook = new XSSFWorkbook(inputStream);
//设置模板的第一个sheet的名称
workbook.setSheetName(0, linkNames.get(0));
//循环表名
Map<String, Integer> map = new HashMap<>();
map.put(linkNames.get(0), 1);
for (int i = 1; i < linkNames.size(); ++i) {
if (map.containsKey(linkNames.get(i))) {
map.put(linkNames.get(i), map.get(linkNames.get(i)) + 1);
workbook.cloneSheet(0, linkNames.get(i) + "_" + map.get(linkNames.get(i)));
} else {
map.put(linkNames.get(i), 1);
workbook.cloneSheet(0, linkNames.get(i));
}
}
//写到流里
workbook.write(bos);
byte[] bArray = bos.toByteArray();
is = new ByteArrayInputStream(bArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
workbook.close();
}
}
return is;
}
写入数据的相关逻辑
ExcelWriter excelWriter = null;
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
try (InputStream is = EasyExcelUtils.getTemplate("template", linkNames,
Constant.FINANCE_RESOURCE)) {
//设置输出流和模板信息
excelWriter = EasyExcelFactory
.write(response.getOutputStream())
.withTemplate(is)
.excelType(ExcelTypeEnum.XLSX).build();
EasyExcelUtils.getExcelStrategy();
//遍历组装excel对象
AtomicInteger index = new AtomicInteger();
AtomicLong no = new AtomicLong();
//组装excel
ExcelWriter finalExcelWriter = excelWriter;
List<AnnualAccumulatedTaxesExcelDto> pojoList = new ArrayList<>();
map.forEach((key, value) -> {
//sheet页名称
String sheetName = value.get(0).getComName();
UserInfoDto infoPojo = new UserInfoDto();
value.forEach(item -> {
//表格信息
UserExcelDto pojo = mapperFacade.map(item, UserExcelDto.class);
pojo.setNo(no.incrementAndGet());
pojoList.add(pojo);
});
infoPojo.setYear(year);
infoPojo.setComName(sheetName);
WriteSheet writeSheet = EasyExcelFactory
.writerSheet(index.getAndIncrement(), sheetName)
.build();
//向sheet写入数据,这里的数据就是重复的数据使用{.xxx}的格式包裹
//传入fillConfig,会在新的行输入数据
finalExcelWriter.fill(pojoList, fillConfig, writeSheet);
//这里的数据是总计的数据,使用{xxx}的格式包裹
finalExcelWriter.fill(infoPojo, writeSheet);
pojoList.clear();
});
excelWriter.finish();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (excelWriter != null) {
excelWriter.close();
}
}
注意
到这里生成excel文件的代码就完了,这个方法建议和我另一篇文章关于excel文件的读取结合使用。另一篇文章提到过读取excel时,因为生成的excel文件版本太老导致读取不到,使用上面的方式生成的excel不会存在这种问题。
附链接(关于java实现excel文件的读取):http://t.csdn.cn/s66DU