需求描述
要求批量導(dǎo)出數(shù)據(jù),以excel的格式。
選擇方式
前臺(tái) + 后臺(tái)
之前在別的項(xiàng)目中也遇到過導(dǎo)出的問題,解決方式是直接在前臺(tái)導(dǎo)出將表格導(dǎo)出。
這次沒有選擇前臺(tái)導(dǎo)出的方式,是由于需要導(dǎo)出所有的數(shù)據(jù),所以考慮直接在后臺(tái)獲取所有的數(shù)據(jù),然后就直接導(dǎo)出,最后前臺(tái)觸發(fā)導(dǎo)出API。
后臺(tái)實(shí)現(xiàn)
導(dǎo)出使用的是POI,在上一篇文章中,我已做了基本的介紹,這里就不做介紹配置了,參照:POI實(shí)現(xiàn)將導(dǎo)入Excel文件
創(chuàng)建表格
首先先建立一張表,這里要建立.xlsx格式的表格,使用XSSFWorkbook:
Workbook workbook = new XSSFWorkbook();Sheet sheet = workbook.createSheet("new sheet");接著創(chuàng)建表格的行和單元格:
Row row = sheet.createRow(0);row.createCell(0);
然后設(shè)置表頭:
row.createCell(0).setCellValue("學(xué)號(hào)");row.createCell(1).setCellValue("姓名");row.createCell(2).setCellValue("手機(jī)號(hào)碼");最后獲取所有的數(shù)據(jù),對應(yīng)的填寫到單元格中:
int i = 1;for (Student student : studentList) { row = sheet.createRow(i); row.createCell(0).setCellValue(student.getStudentNumber()); row.createCell(1).setCellValue(student.getName()); row.createCell(2).setCellValue(student.getPhoneNumber()); i++;}輸出
這部分是糾結(jié)比較久的,反復(fù)試了很多次。
一開始是直接以文件輸出流的形式輸出的:
FileOutputStream output = new FileOutputStream("test.xlsx");workbook.write(output);這樣可以正確生成文件,但是問題是,它會(huì)生成在項(xiàng)目的根目錄下。
而我們想要的效果是,下載在本地自己的文件夾中。
要解決這個(gè)問題,需要添加相應(yīng)信息,返回給瀏覽器:
OutputStream fos = response.getOutputStream();response.reset();String fileName = "test";fileName = URLEncoder.encode(fileName, "utf8");response.setHeader("Content-disposition", "attachment;filename="+ fileName+".xlsx");response.setCharacterEncoding("UTF-8");response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");workbook.write(fos);fos.close();后臺(tái)完成代碼:
public void batchExport(HttpServletResponse response) { logger.debug("創(chuàng)建工作表"); Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("new sheet"); logger.debug("獲取所有學(xué)生"); List<Student> studentList = (List<Student>) studentRepository.findAll(); logger.debug("建立表頭"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("學(xué)號(hào)"); row.createCell(1).setCellValue("姓名"); row.createCell(2).setCellValue("手機(jī)號(hào)碼"); logger.debug("將學(xué)生信息寫入對應(yīng)單元格"); int i = 1; for (Student student : studentList) { row = sheet.createRow(i); row.createCell(0).setCellValue(student.getStudentNumber()); row.createCell(1).setCellValue(student.getName()); row.createCell(2).setCellValue(student.getPhoneNumber()); i++; } OutputStream fos; try { fos = response.getOutputStream(); response.reset(); String fileName = "test"; fileName = URLEncoder.encode(fileName, "utf8"); response.setHeader("Content-disposition", "attachment;filename="+ fileName+".xlsx"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");// 設(shè)置contentType為excel格式 workbook.write(fos); fos.close(); } catch (Exception e) { e.printStackTrace(); }}
新聞熱點(diǎn)
疑難解答
圖片精選