POI复制Excel模板并填充数据

一、复制模板

private static File createNewFile() {
		// 读取模板,并赋值到新文件************************************************************
		// 文件模板路径
		String path = (getSispPath());
		File file = new File(path);
		if (!file.exists()) {
			logger.error("原模板文件不存在");
			System.out.println("原模板文件不存在");
		}
		// 保存文件的路径
		String realPath = file.getParent();
		// 新的文件名
		String newFileName = "statement-" + System.currentTimeMillis() + ".xlsx";
		// 判断路径是否存在
		File dir = new File(realPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		// 写入到新的excel
		File newFile = new File(realPath, newFileName);
		try {
			newFile.createNewFile();
			// 复制模板到新文件
			fileChannelCopy(file, newFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newFile;
	}

写入数据

public static void exportExcel(SettlementBean bean,HttpServletResponse response) {

	File newFile = createNewFile();
	InputStream is = null;
	XSSFWorkbook workbook = null;
	XSSFSheet sheet = null;
	try {
		is = new FileInputStream(newFile);// 将excel文件转为输入流
		workbook = new XSSFWorkbook(is);// 创建个workbook,
		// 获取第一个sheet
		sheet = workbook.getSheetAt(0);
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	if (sheet != null) {
		try {
			sheet.setForceFormulaRecalculation(true);//保留模板格式  计算公式
			FileOutputStream fos = new FileOutputStream(newFile);
			//写入数据
			//batch
			XSSFCell cell1 = sheet.getRow(2).getCell(3);
			cell1.setCellValue("batch."+bean.getBatch());
                        sheet.shiftRows(rowIndex, sheet.getLastRowNum(), extenSize,true,false);//插入行
			for (int j = rowIndex; j < rowIndex+extenSize; j++) {//创建表格
				sheet.createRow(j);
				for (int j2 = 4; j2 < 8; j2++) {
					sheet.getRow(j).createCell(j2);
				}					}
                        workbook.write(fos);
			fos.flush();
			fos.close();
			// 下载
			InputStream fis = new BufferedInputStream(new FileInputStream(
					newFile));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
		
			response.reset();
			response.setContentType("text/html;charset=UTF-8");
			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			response.setContentType("application/x-msdownload");
			String newName = URLEncoder.encode(
				"statement-" + bean.getMerchantNo() + ".xlsx",
				"UTF-8");
			response.addHeader("Content-Disposition",
				"attachment;filename=\"" + newName + "\"");
			response.addHeader("Content-Length", "" + newFile.length());
			toClient.write(buffer);
			toClient.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != is) {
					is.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
}

代码并不能直接运行,需根据自己实际需求修改。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值