1. 程式人生 > >根據資料批量生成excel檔案

根據資料批量生成excel檔案

第一步匯入依賴:

<!--excel支援-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</
artifactId> <version>3.11</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11</version> </dependency>

第二步前端控制器實現:

/**
 * 檔案匯出功能
 */
@GetMapping("/test")
public 
String export(HttpServletResponse response){ //查詢所有區域資訊 List<String> list = new ArrayList<>(); list.add("aaa"); list.add("bbb"); list.add("ccc"); List<String> list2=new ArrayList<>(); list2.add("ddd"); list2.add("eee"); list2.add("fff"); //
建立Excel 工作物件 // HSSFWorkbook hssfWorkbook=new HSSFWorkbook(); //使用最新的工作物件 SXSSFWorkbook sxssfWorkbook=new SXSSFWorkbook(); for (String s : list2) { //建立sheet //HSSFSheet sheet = hssfWorkbook.createSheet(s); Sheet sheet = sxssfWorkbook.createSheet(s); Row row = sheet.createRow(0); //建立行 // HSSFRow row = sheet.createRow(0); //建立表空間欄位 row.createCell(0).setCellValue("區域編號"); row.createCell(1).setCellValue("省份"); row.createCell(2).setCellValue(""); row.createCell(3).setCellValue("區縣"); //遍歷集合建立表資訊 for (int i = 0; i < list.size(); i++) { //獲得區域物件 String area2 = list.get(i); //建立行 // HSSFRow createRow = sheet.createRow(i+1); Row createRow = sheet.createRow(i + 1); //建立行內欄位 createRow.createCell(0).setCellValue(area2); } } //建立檔名 String filename="fq3.xlsx"; //建立輸出物件 OutputStream out ; response.setContentType("application/ms-excel;charset=UTF-8"); try {
response.setHeader( "Content-Disposition", "attachment;filename=" +
        new String( filename.getBytes("gb2312"), "ISO8859-1" ) );
out = response.getOutputStream (); sxssfWorkbook.write (out ); // 將資料寫出去 String str = " 匯出 " + filename + " 成功! "; System. out.println (str ); out.close (); } catch (Exception e ) { e.printStackTrace (); e.printStackTrace (); String str1 = " 匯出 " + filename + " 失敗! "; System. out.println (str1 ); } return null; }

第三步測試頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試頁面</title>
    <script src="./ckplayer/ckplayer.js"></script>
</head>
<body>
<!--<a href="/group/download?from=1528770630000&to=1529029830000">下載</a>-->
<a href="/dome/test"></a>
</body>
</html>

第四步實現效果: