Springboot+Layui实现数据Excel表格导出
前端代码:
<button type="button" lay-event="add" class="layui-btn layui-btn-sm layui-btn-radius" lay-submit="" lay-filter="doOutPortExcel">
<i class="layui-icon layui-icon-normal"></i>导出Excel疫情数据
</button>
// 导出Excel数据
form.on("submit(doOutPortExcel)", function () {
window.location.href = "/excelOutPortChina";
})
后端代码:
/*
导出Excel数据到文件中,中国疫情数据
1.查询数据库,获取所有疫情数据
2.建立Excel数据对象,封装数据,输出文件
3.建立输出,将封装好的Excel表格导出
*/
@RequestMapping("/excelOutPortChina")
public void excelOutPortChina(HttpServletResponse response) throws Exception {
// 1.查询数据库【查询所有,复核人条件的数据给你查询来】
List<NocvData> list = indexService.list();
// 2.建立Excel对象,封装数据
response.setCharacterEncoding("UTF-8");
// 2.1 创建Excel对象
HSSFWorkbook wb = new HSSFWorkbook();
// 2.2 创建sheet对象
HSSFSheet sheet = wb.createSheet("数据sheet1");
// 2.3 创建表头
HSSFRow hssfRow = sheet.createRow(0);
hssfRow.createCell(0).setCellValue("城市名称");
hssfRow.createCell(1).setCellValue("确诊数量");
// 3.遍历数据,封装Excel公作对象
for (NocvData data : list){
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
dataRow.createCell(0).setCellValue(data.getName());
dataRow.createCell(1).setCellValue(data.getValue());
}
// 4.建立输出流,输出浏览器文件
OutputStream os = null;
// 4.1 设置一下excel名字,输出类型编码
response.setContentType("application/octet-stream;chartset=utf8");
response.setHeader("Content-Disposition","attachment;filename="+ new String("疫情数据表".getBytes(),"iso-8859-1")+".xls");
// 4.2 输出文件
os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
}
}