java后端導出excel表格


轉載 :https://www.cnblogs.com/zhaoyuwei/p/9038135.html

不需要在實體類些@Excel(name = "登錄名", width = 16, orderNum = "1")這些

 1 @RequestMapping("/exportExcel.do")
 2 public void export(HttpServletResponse response) {
 3         //從數據庫查詢出數據
 4         List<User> list = userService.selectAll();
 5         // 創建excel
 6         HSSFWorkbook wk = new HSSFWorkbook();
 7         // 創建一張工作表
 8         HSSFSheet sheet = wk.createSheet("用戶表");
 9         // 設置工作表中的1-3列的寬度
10         sheet.setColumnWidth(0, 5000);
11         sheet.setColumnWidth(1, 5000);
12         sheet.setColumnWidth(2, 5000);
13         //創建第一行
14         HSSFRow row1 = sheet.createRow(0);
15         // 創建第一行的第一個單元格
16         // 向單元格寫值
17         HSSFCell cell = row1.createCell(0);
18         cell.setCellValue("用戶表");
19         //合並單元格CellRangeAddress構造參數依次表示起始行,截止行,起始列,截至列。
20         //0表示 第一行第一列
21         sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));
22         //創建第二行
23         HSSFRow row2 = sheet.createRow(1);
24         row2.createCell(0).setCellValue("登錄名");
25         row2.createCell(1).setCellValue("年齡");
26         row2.createCell(2).setCellValue("昵稱");
27 
28         // 創建第一行
29         for (int i = 0; i < list.size(); i++) {
30             //創建行    一條數據一行
31             HSSFRow row = sheet.createRow(i + 2);
32             row.createCell(0).setCellValue(list.get(i).getName());
33             row.createCell(1).setCellValue(list.get(i).getAge());
34             row.createCell(2).setCellValue(list.get(i).getNickName());
35         }
36         try {
37             /**
38              * 彈出下載選擇路徑框
39              */
40             Date date = new Date();
41             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
42             String str = sdf.format(date);
43             response.setContentType("application/octet-stream");
44             response.setHeader("Content-disposition", "attachment;filename=" + str + ".xls");// 默認Excel名稱
45             response.flushBuffer();
46             wk.write(response.getOutputStream());
47             // wk.write(new FileOutputStream(new File("D://daochu")));
48             wk.close();
49         } catch (IOException e) {
50             e.printStackTrace();
51         }
52 
53     }

 

前端代碼和js

 

<input type="button" value="導出" class="ui_input_btn01" id="daochule" />


$(function () {
$("#daochule").click(function () {
window.location.href="exportExcel.do";
})
})

 

依賴

 1 <!--導出的核心依賴-->

  <dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.2.0</version>
  </dependency>

 
        

就可以直接導出excel表

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM