將datagrid表格資料匯出為Excel(動態列)
阿新 • • 發佈:2019-01-07
【需求】:當datagrid表格顯示的每列的欄位名稱並不固定,如要求每列欄位為日期,這樣的話,我們不能從新定義實體來接收這個欄位,因為不同的條件,後臺返回的資料的時間也不會固定,而這時用常用的匯出Excel的工具就會遇到些麻煩。
【解決】:(直接上程式碼)
@RequestMapping(value={"/scheduleExport"}, method={org.springframework.web.bind.annotation.RequestMethod.POST, org.springframework.web.bind.annotation.RequestMethod.GET}) public void scheduleExport(Integer rowCount, Integer current, String keyword, Pagination page, Model model, HttpServletRequest request, HttpServletResponse response) { page.clearSorts(); Map params = new HashMap(); params.put("param1", this.strScript); params.put("param2", page); List listResult = this.zHGLGLOBALSEARCHService.searchSqlList(params); List list1key = new ArrayList(); list1key = GetMapKey(listResult); WritableWorkbook wwb = null; OutputStream os = null; try { os = response.getOutputStream(); wwb = Workbook.createWorkbook(os); WritableSheet ws = wwb.createSheet("全域性搜尋", 0); int size = list1key.size(); String[] heads = (String[])list1key.toArray(new String[size]); insertHead(ws, heads); int rownum = 1; if ((listResult != null) && (listResult.size() > 0)) { for (int i = 0; i < listResult.size(); i++) { Map schedule = (Map)listResult.get(i); for (int j = 0; j < heads.length; j++) { insertCell(ws, null, rownum, j, schedule.get(list1key.get(j)).toString()); } rownum++; } } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); response.setContentType("application/msexcel"); response.addHeader("Content-disposition", "attachment;filename=schedule_" + sdf.format(new Date()) + ".xls"); wwb.write(); } catch (Exception e) { e.printStackTrace(); try { if (wwb != null) wwb.close(); if (os != null) os.close(); } catch (Exception e) { e.printStackTrace(); } } finally { try { if (wwb != null) wwb.close(); if (os != null) os.close(); } catch (Exception e) { e.printStackTrace(); } } } private static void insertHead(WritableSheet ws, String[] heads) throws Exception { WritableFont font1 = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD); WritableCellFormat format1 = new WritableCellFormat(font1); format1.setAlignment(Alignment.CENTRE); for (int i = 0; i < heads.length; i++) { WritableCell cell = new Label(i, 0, heads[i]); cell.setCellFormat(format1); ws.addCell(cell); } } private static void insertCell(WritableSheet ws, WritableCellFormat format1, int row, int column, String name) throws WriteException, RowsExceededException { WritableCell cell = new Label(column, row, name); if (format1 != null) { cell.setCellFormat(format1); } ws.addCell(cell); }