1.在pom.xml中添加poi依賴
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
2.主要代碼
(1)controller層
/** * Excel表格導出接口 * http://localhost:端口號/ExcelDownload * @param response response對象 * @throws IOException 拋IO異常 */ @ApiOperation("導出接口") @PostMapping("/ExcelDownload") public void excelDownload(HttpServletResponse response) throws IOException { uploadService.export(response); }
(2)service層
public void export(HttpServletResponse response){ //表頭數據 String[] header = {"主鍵", "姓名", "生日", "創建時間", "母親", "學校","年齡"}; //聲明一個工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); //生成一個表格,設置表格名稱為"學生表" HSSFSheet sheet = workbook.createSheet("學生表"); //設置表格列寬度為10個字節 sheet.setDefaultColumnWidth(10); //創建標題的顯示樣式 HSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); //創建第一行表頭 HSSFRow headrow = sheet.createRow(0); //遍歷添加表頭(下面模擬遍歷學生,也是同樣的操作過程) for (int i = 0; i < header.length; i++) { //創建一個單元格 HSSFCell cell = headrow.createCell(i); //創建一個內容對象 HSSFRichTextString text = new HSSFRichTextString(header[i]); //將內容對象的文字內容寫入到單元格中 cell.setCellValue(text); cell.setCellStyle(headerStyle); } //獲取所有的student數據 List<Student> emps=uploadMapper.getStudentData(); for(int i=0;i<emps.size();i++){ //創建一行 HSSFRow row1 = sheet.createRow(i+1); //第一列創建並賦值 row1.createCell(0).setCellValue(new HSSFRichTextString(emps.get(i).getId().toString())); //第二列創建並賦值 row1.createCell(1).setCellValue(new HSSFRichTextString(emps.get(i).getName())); //第三列創建並賦值 row1.createCell(2).setCellValue(new HSSFRichTextString(emps.get(i).getBirthday())); //第四列創建並賦值-最高學歷 row1.createCell(3).setCellValue(new HSSFRichTextString(emps.get(i).getCreateTime())); //第五列創建並賦值-最高學歷 row1.createCell(4).setCellValue(new HSSFRichTextString(emps.get(i).getMother())); //第六列創建並賦值-最高學歷 row1.createCell(5).setCellValue(new HSSFRichTextString(emps.get(i).getSchool())); //第七列創建並賦值-最高學歷 row1.createCell(6).setCellValue(new HSSFRichTextString(String.valueOf(emps.get(i).getAge()))); } //准備將Excel的輸出流通過response輸出到頁面下載 //八進制輸出流 response.setContentType("application/octet-stream"); //這后面可以設置導出Excel的名稱,此例中名為student.xls response.setHeader("Content-disposition", "attachment;filename=employee.xls"); try { //刷新緩沖 response.flushBuffer(); //workbook將Excel寫入到response的輸出流中,供頁面下載 workbook.write(response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } }
3.在postman中進行測試(http://localhost:端口號/ExcelDownload)
3.數據導出結果

final:不積跬步,無以至千里.不積小流,無以成江海
