java中使用POI+excel 實現數據的批量導入和導出


java web中使用POI實現excel文件的導入和導出

 

文件導出

 1     //導入excle表
 2     public String exportXls() throws IOException{
 3         //1.查詢所有需要的數據
 4         List<Subarea> list = subareaService.findAll();
 5         //2.使用POI將數據寫進excel表中
 6         //2.1在內存中創建一個excel文件
 7         HSSFWorkbook workbook = new HSSFWorkbook();
 8         //2.2創建一個標簽頁
 9         HSSFSheet sheet = workbook.createSheet("分區數據");
10         //2.3創建標題行
11         HSSFRow headRow = sheet.createRow(0);
12         headRow.createCell(0).setCellValue("分區編號");
13         headRow.createCell(1).setCellValue("開始編號");
14         headRow.createCell(2).setCellValue("結束編號");
15         headRow.createCell(3).setCellValue("位置信息");
16         headRow.createCell(4).setCellValue("省市區");
17         //2.4將需要的數據放入excel表中
18         for (Subarea subarea : list) {
19             HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
20             headRow.createCell(0).setCellValue(subarea.getId());
21             headRow.createCell(1).setCellValue(subarea.getStartnum());
22             headRow.createCell(2).setCellValue(subarea.getEndnum());
23             headRow.createCell(3).setCellValue(subarea.getPosition());
24             headRow.createCell(4).setCellValue(subarea.getRegion().getName());
25         }
26         
27         //3.輸出流進行文件下載
28         String filename = "分區信息表.xls";
29         String mimeType = ServletActionContext.getServletContext().getMimeType(filename);
30         ServletOutputStream outs = ServletActionContext.getResponse().getOutputStream();
31         
32         
33         //獲取客戶端的瀏覽器類型
34         String agent = ServletActionContext.getRequest().getHeader("User-Agent");
35         filename =  FileUtils.encodeDownloadFilename(filename, agent);
36         ServletActionContext.getResponse().setHeader("content-disposition", 
37                 "attachment;filename"+filename);
38         
39         workbook.write(outs);
40         return NONE;
41     }

針對不同瀏覽器下載使用的工具類

    /**
     * 下載文件時,針對不同瀏覽器,進行附件名的編碼
     * 
     * @param filename
     *        下載文件名
     * @param agent
     *        客戶端瀏覽器
     * @return 編碼后的下載附件名
     * @throws IOException
     */
    public static String encodeDownloadFilename(String filename, String agent) throws IOException {
        if (agent.contains("Firefox")) { // 火狐瀏覽器
            filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?=";
            filename = filename.replaceAll("\r\n", "");
        } else { // IE及其他瀏覽器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        return filename;
    }

 


免責聲明!

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



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