【根据excel模板写入数据并分页多sheet导出】

根据excel模板写入数据并分页多sheet导出

这是前段时间遇到的一个需求,当时看了一些大佬们文档,花了一些时间才搞定的。功能到是实现了,就是不知道怎样写可以更优雅一些,现在贴出来记录一下:

主要思路大概分为以下几步:

  1. 导入相关poi依赖
  2. 根据路径读取模板,建立workbook对象,获取模板sheet页
  3. 将数据列表遍历并复制模板页建立新的sheet,填充数据
  4. 填充完写入到本地文件中

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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值