效果图
前端代码
exportExcelAll(){
window.location.href = getBaseUrl() + 'Action/excelDataAll?happenDate='+this.params.happenDate;
},
后端代码
try{
Workbook workbook=new XSSFWorkbook();
//创建sheet
Sheet sheet1=workbook.createSheet("结果总数拦截记录");
//写入sheet数据
//表头
JSONObject head=new JSONObject();
head.put("deptname","科室名称");
//表头属性
List<String> props=Arrays.asList("deptname");
//第一个sheet的数据
JSONObject obj1=getDeptShjlDetails(happenDate,strDate,endDate,null,"结果总数",null,null,null,null,null,"","",gzlx);
JSONArray arr1=obj1.getJSONArray("list");
//创建单元格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//组装数据
this.setData(sheet1,props,head,arr1,cellStyle);
//导出excel文件
res.reset();
ServletOutputStream outputStream=res.getOutputStream();
//转为字节流
ByteArrayOutputStream os = new ByteArrayOutputStream();
workbook.write(os);
workbook.close();
byte[] bytes = os.toByteArray();
res.setContentType("application/pdf;charset=UTF-8");
res.setHeader("Content-Disposition", "attachment;filename=" + new String(("全部科室拦截记录.xlsx").getBytes("utf-8"), "iso-8859-1"));
res.setContentLength(bytes.length);
outputStream.write(bytes, 0, bytes.length);
outputStream.flush();
}catch (Exception e){
e.printStackTrace();
}
private void setData(Sheet sheet,List<String> props,JSONObject head,JSONArray arr,CellStyle cellStyle){
//创建表头
Row row=sheet.createRow(0);
for(int j=0;j<props.size();j++){
//创建列
Cell cell=row.createCell(j);
cell.setCellValue(head.getString(props.get(j)));
cell.setCellStyle(cellStyle);
}
//创建表数据
for(int i=0;i<arr.size();i++){
//创建行
Row rowData=sheet.createRow(i+1);
for(int j=0;j<props.size();j++){
//创建列
Cell cell=rowData.createCell(j);
Record record= (Record) arr.get(i);
cell.setCellValue(record.getString(props.get(j)));
cell.setCellStyle(cellStyle);
}
}
}