1. 程式人生 > >Excel表單的匯入匯出工具類(一)

Excel表單的匯入匯出工具類(一)

對報表的處理無外乎匯入匯出,之前也做過不少,但都一直沒有相關記錄。用順手的東西就不要拋棄,而是改裝接著用。這樣開發效率才能提高。

1.可以用模板方式來設定匯入資料的excel模板。並獲取該模板

1.1 建立模板

模板建立就是在按照頁面的顯示欄位,整理出查詢列。如下圖紅色部分。

這裡寫圖片描述

1.2 讀取模板

關鍵是獲取模板在本地專案的路徑。獲取路徑有兩種區分。一種在src下,一種是在webapp下。具體可以看前面筆記中記載。
我這裡說放在webapp下的情況:模板放在excelModel資料夾中。

String path=request.getSession().getServletContext
().getRealPath("excelModel"); path=path.replace("\\","/");

2.模板寫入的工具類

//filePath  模板檔案在專案的路徑
//list  要匯出的資料集合
public static Workbook buildWorkBook2(String filePath,List<List<String>> list){
    FileInputStream fs=null;
    String name=new String(filePath.trim.getBytes(),Charset.forName("UTF-8"
)); File file=new File(name); String fileName=file.getName(); if(file.exists()){ try{ fs=new FileInputStream(file); }catch(FileNotFoundException e){ logger.error("獲取模板檔案流時異常",e); } String suffex=fileName.substring(fileName.lastIndexOf(".")); Workbook web=null; try{ web =suffex.equals(".xlsx"
)? new SXSSFWorkbook(new XSSFWorkbook(fs),200):new HSSFWorkbook(fs); Sheet sheet =web.getSheetAt(0); if(list !=null && list.size()>0){ int dataRows =list.size(); //填充資料 if(int i=0;i<dataRows; i=+){ Row row=sheeet.createRow(i+2); List<String> current=list.get(i); int cells=current.size(); for(int j=0; j<=cells; j++){ Cell cell=row.createCell(j,Cell.CELL_TYPE_STRING); if(j==0){ cell.setCellValue(i+1); } if(current.get(j-1)==null || TKStringUtils.isEmpty(current.get(j-1)) || current.get(j-1).equals("null")){ cell.setCellValue(""); }else{ cell.setCellValue(String.valueOf(current.get(j-1))); } } } } }catch(Exception e){ throw new RuntimeException(e); }finally{ if(fs !=null){ try{ fs.close(); }catch(IOException e){ logger.error("資料匯出時,關閉檔案流異常。"); } } } } return web; }

3.填充資料後返回頁面時用到的工具類

public static void renderExcel(Workbook web,HttpServletResponse response){
    response.setContentType("application/octet-stream");
    try{
    response.addHeader("Content-Disposition","attachement;filename="+URLEncoder.encode(web.getSheetName(0)+".xlsx","utf-8"));
    OutputStream out=response.getOutputStream();
    web.write(out);
    out.flush();
    out.close();
    }catch(Exception e){
        throw new RuntimeException(e);
    }
}

4.全程式碼預覽

這裡寫圖片描述