实现功能:
- 后台将信息从从数据库查询出来
- 将查询到的信息写入excel表,将其输出供前端下载
提示
- 使用Apache POI 提供的HSSFWorkbook类实现对excel的操作
代码实现,只po出controller层(规范代码应将具体功能实现写在service层,controller直接接受前端参数调用方法即可),直接用浏览器访问或者postman测试即可以下载,
@RequestMapping("excelDownloads")
public void downloadAllClassmate(HttpServletResponse response,Patent patent1) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("信息表");
List<Patent> patentExcle = patentService.selectTest();
String fileName = "patentExcel" + ".xls";//设置要导出的文件的名字
//新增数据行,并且设置单元格数据
int rowNum = 1;
String[] headers = { "专利ID", "批次", "案例文号", "申请号", "申请时间", "技术联系人", "申请人", "创建人", "专利名", "审核状态", "专利状态", "发明类型", "发明人", "撰写人", "备注", "状态", "创建人名称", "撰写人名称"};
//headers表示excel表中第一行的表头
HSSFRow row = sheet.createRow(0);
//在excel表中添加表头
for(int i=0;i<headers.length;i++){
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//在表中存放查询到的数据放入对应的列
for (Patent patent : patentExcle) {
HSSFRow row1 = sheet.createRow(rowNum);
row1.createCell(0).setCellValue(patent.getPatentId());
row1.createCell(1).setCellValue(patent.getPatentBatch());
row1.createCell(2).setCellValue(patent.getPatentCaseNum());
row1.createCell(3).setCellValue(patent.getPatentApplyNum());
row1.createCell(4).setCellValue(patent.getPatentApplyTime());
row1.createCell(5).setCellValue(patent.getPatentTechnicalContact());
row1.createCell(6).setCellValue(patent.getPatentApplyPerson());
row1.createCell(7).setCellValue(patent.getPatentCreatePerson());
row1.createCell(8).setCellValue(patent.getPatentName());
row1.createCell(9).setCellValue(patent.getPatentSign());
row1.createCell(10).setCellValue(patent.getPatentStatusId());
row1.createCell(11).setCellValue(patent.getPatentType());
row1.createCell(12).setCellValue(patent.getPatentInventor());
row1.createCell(13).setCellValue(patent.getPatentWriter());
row1.createCell(14).setCellValue(patent.getPatentRemarks());
row1.createCell(15).setCellValue(patent.getStatusName());
row1.createCell(16).setCellValue(patent.getCreatePersonName());
row1.createCell(17).setCellValue(patent.getWriterName());
rowNum++;
}
response.setContentType("application/x-xls;charset=utf-8");
//response.setContentType("application/octet-stream");//设置发送到客户端的响应的内容类型,application/octet-stream( 二进制流,不知道下载文件类型)
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));//这样写文件名中文不会乱码
response.flushBuffer();
ServletOutputStream out = response.getOutputStream();//输出流
workbook.write(out); //输出文件
out.close(); //关闭流,不主动关闭也能下载,不过会报错
}