POI按模板导出Excel刷新公式

通过POI导出excel,若是原excel模板中包含公式,默认情况下公式是不起作用的。需要通过添加下面这一行代码: sheet.setForceFormulaRecalculation(true);

基本案例:默认excel模板样式

其中C列是通过A列+B列的结果;

	public final void fnTestExcel() throws IOException {
		int rows = 3, cols = 2;
	//	File excel = FileUtil.getFileAtClassesDir(null, "W005/templete/", "test.xls");
		File excel=new File("E:\\gitworkspace\\bpeyixi\\src\\main\\resources\\W005\\templete\\test.xls");//模板文件
		FileInputStream is = new FileInputStream(excel);
		String fileName="test2";
		HSSFWorkbook wb = new HSSFWorkbook(is);
		HSSFSheet sheet = wb.getSheetAt(0);// 打开第一个sheet
		HSSFRow row = sheet.getRow(0);// 打开第一行
		for (int i = 0; i < rows; i++) {
			row = sheet.getRow(i);
			for(int k=0;k<cols;k++) {
				Cell cell = row.getCell(k);
				cell.setCellType(Cell.CELL_TYPE_STRING);
				int testInt=i+k+2;
				cell.setCellValue(testInt+"");// 
			}
		}
		sheet.setForceFormulaRecalculation(true);//刷新公式
		OutputStream os = null;
		try {
			// 设置生成的文件类型
			response.setContentType("application/vnd.ms-excel;charset=utf-8");// 设置生成的文件类型
			response.setHeader("Content-Disposition", "filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));// 设置文件头编码方式和文件名
			os = response.getOutputStream();
			wb.write(os);
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (Exception e) {
			}
		}

	}

涉及到的类:

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

导出结果

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值