java實現excel下載功能例項
阿新 • • 發佈:2018-12-12
其實需求很簡單,就是點選按鈕後,向後臺傳入查詢條件,然後根據查詢條件獲取滿足條件的記錄通過excel下載。
方案一:使用ajax方式不可以原因
匯出excel算是檔案下載了,後臺需要向前臺(瀏覽器)寫檔案流,而ajax請求獲取的資料的都是字串(此點當時在除錯頁面的時候,Response響應中滿是亂碼的字串文字),它沒法解決後臺返回的檔案流,但是瀏覽器可以。
換句話說 ajax貌似實現不了檔案下載的功能,所以使用window.location.href直接地址重定向
前端jsp程式碼:
<button class="saveRH bi-btn bi-btn-primary" onclick="exportUserPage()">匯出當前頁</button>
js程式碼:
function exportUserPage(){ var pageNow = $("#pageNow").val(); var gender = ""; $('input[name="gender"]:checked').each(function(){ gender += $(this).val()+","; }); gender = deleteLastComma(gender); var age = $('input[name="age"]').val(); var experience = $('input[name="experience"]').val(); var json = { gender:gender, age:age, experience:experience, pageNow:pageNow } // 注意這裡因為url中有中文等字元,所以需要編碼 location.href=encodeURI('/userFilter/exportUserPage.action?parameterMap='+ JSON.stringify(json)); }
後端接收請求程式碼
@RequestMapping(value="/exportUserPage.action") public void exportUserPage( HttpServletResponse response,HttpServletRequest request){ Map parameterMap = null; try { // 對應前端的編碼,在這裡進行解碼,並解析json為Map String value = URLDecoder.decode(request.getParameter("parameterMap"), "UTF-8"); parameterMap = (Map)JSON.parse(value); System.out.println("value"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Map<String, String> queryCondition = parameterToQueryCondition(parameterMap); // 1 獲取當前頁數 Object pageObj = parameterMap.get(GeneralConstants.PAGE_NOW); Integer pageNow = PageUtil.getPage(pageObj); // 2 獲取實際資料 int start = (pageNow - 1) * PAGE_SIZE;//開始條數 int end = PAGE_SIZE; List<Map<String, Object>> list = userFilterService.listDataWithPage(start,end,queryCondition); // 3 生成excel String []title = {"UID","姓名","學歷","姓別","求職狀態","求職期望","是否有boss身份","期望工作地區","工作年限","工作經歷","教育經歷"}; HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("SheetName",title,list,null); // 4 響應到客戶端,彈出下載提示框 try { this.setResponseHeader(response, "user"+DateUtil.getCurrentDate()+".xls"); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); logger.error("excel匯出錯誤:"+e); } return ; } /** * 功能描述: 傳送響應流方法 * * @param * @return * @auther mazhen * @date 2018/12/11 下午2:17 */ public void setResponseHeader(HttpServletResponse response, String fileName) { try { try { fileName = new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("excel匯出錯誤:"+e); } response.setContentType("application/octet-stream;charset=ISO8859-1"); response.setHeader("Content-Disposition", "attachment;filename="+ fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); logger.error("excel匯出錯誤:"+ex); } }
下面是excel生成類
public class ExcelUtil {
/**
* 匯出Excel
* @param sheetName sheet名稱
* @param title 標題
* @param mapList 內容
* @param wb HSSFWorkbook物件
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, List<Map<String,Object>> mapList, HSSFWorkbook wb){
// 第一步,建立一個HSSFWorkbook,對應一個Excel檔案
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中新增一個sheet,對應Excel檔案中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制
HSSFRow row = sheet.createRow(0);
// 第四步,建立單元格,並設定值表頭 設定表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式
//宣告列物件
HSSFCell cell = null;
//建立標題
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
Map<String, Object> map = null;
//建立內容
for(int i=0;i<mapList.size();i++){
map = mapList.get(i);
row = sheet.createRow(i + 1);
//將內容按順序賦給對應的列物件
row.createCell(0).setCellValue( map.get("user_id").toString());
row.createCell(1).setCellValue((String) map.get("name"));
row.createCell(2).setCellValue((String) map.get("degree"));
row.createCell(3).setCellValue((String) map.get("gender"));
row.createCell(4).setCellValue((String) map.get("apply_status"));
row.createCell(5).setCellValue(map.get("l1_name_a")+","+map.get("city_a")+","+map.get("level_a")+","+map.get("salary_a")+";"+
map.get("l1_name_b")+","+map.get("city_b")+","+map.get("level_b")+","+map.get("salary_b")+";"+
map.get("l1_name_c")+","+map.get("city_c")+","+map.get("level_c")+","+map.get("salary_c")+";"
);
row.createCell(6).setCellValue((String) map.get("is_boss"));
row.createCell(7).setCellValue( map.get("city_a")+","+map.get("city_b")+","+map.get("city_c"));
row.createCell(8).setCellValue((String) map.get("work_years"));
row.createCell(9).setCellValue((String) map.get("work_description"));
row.createCell(10).setCellValue((String) map.get("edu_description"));
}
return wb;
}
}
開發過程中也遇到一些問題,如400錯誤等,可以參考:https://blog.csdn.net/h2604396739/article/details/84954626