java导出excel自动计算公式

最近在开发过程中,遇到java读取excel模板并写入数据,其中数据有计算求和的操作,一开始没有实现导出自动计算公式,所以费了一遍事,后台又重新做了一次数据计算,总感觉这样不是很好,所以上网找资料,终于在同事的帮助下实现了这一功能,分享出来,希望自己或看到的人可以受用。
String realPath= request.getSession().getServletContext().getRealPath("/WEB-INF/templetefile");
File templeteFile = new File(realPath + "/examNotice.xlsx");
InputStream fis = new FileInputStream(templeteFile);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet st = wb.getSheetAt(0);
XSSFCell cell = null;
String[] rowName = {"LEVEL_5","LEVEL_4","LEVEL_3"};
for(int i=9;i<12;i++){
int k = 1;
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map map = (Map)entry.getValue();
cell = st.getRow(i).getCell(k);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);//设置单位格类型
cell.setCellValue(Double.valueOf(map.get(rowName[i-9]).toString()));
k++;
}
}
st.setForceFormulaRecalculation(true);//重点在这,这句是重新计算公式的意思
if(request.getHeader("user-agent").indexOf("MSIE") != -1) {
filename = java.net.URLEncoder.encode(filename,"utf-8") + ".xlsx";
        } else {
        filename = new String(filename.getBytes("utf-8"),"iso-8859-1") + ".xlsx";
        }
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
wb.write(bStream);
ByteArrayInputStream bInputStream = new ByteArrayInputStream(bStream.toByteArray());
response.setContentLength(bStream.size());
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+ filename);
byte[] bt = new byte[1024];
int bcount = 0;
while((bcount = bInputStream.read(bt,0,1024)) != -1){
response.getOutputStream().write(bt,0,bcount);
}
response.getOutputStream().flush();

你可能感兴趣的:(excel公式)