POI按模板导出Excel刷新公式

    xiaoxiao2022-07-14  266

    通过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;

    导出结果

     

    最新回复(0)