根据excel模板写入数据并分页多sheet导出
这是前段时间遇到的一个需求,当时看了一些大佬们文档,花了一些时间才搞定的。功能到是实现了,就是不知道怎样写可以更优雅一些,现在贴出来记录一下:
主要思路大概分为以下几步:
- 导入相关poi依赖
- 根据路径读取模板,建立workbook对象,获取模板sheet页
- 将数据列表遍历并复制模板页建立新的sheet,填充数据
- 填充完写入到本地文件中
poi依赖,需要注意一下版本必须一样:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.12</version>
</dependency>
<!--读取excel文件-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
主要实现代码:
......
//定义文件对象,输入,输出流对象
File file = new File(machinePurchaseExcel);
FileInputStream fis;
FileOutputStream fos;
//获取采购单模板
fis = new FileInputStream(file);
//根据模板创建Excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//定义模板页
HSSFSheet sheet = workbook.getSheetAt(0);
//定义新页面
HSSFSheet newSheet;
//定义map封装简单数据
Map<String,Object> tmp =new HashMap<>(0);
//设置年月日
Calendar calendar = Calendar.getInstance();
tmp.put("year", calendar.get(Calendar.YEAR) + "");
String month = (calendar.get(Calendar.MONTH) + 1) + "";
tmp.put("month", month);
tmp.put("day", day);
//遍历输出多个sheet页
for (int i = 0; i < tmpList.size(); i++) {
// 设置新建Sheet的页名
newSheet = workbook.createSheet("sheet"+(i+1));
// 将模板中的内容复制到新建的Sheet页中
ExcelUtil.copySheet(