首先準備實體類以及數(shù)據(jù) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public class DemoData { @ExcelProperty({"主題","字符串標題"}) private String string; @ExcelProperty({"主題","日期標題"}) private Date date; @ExcelProperty({"主題","數(shù)字標題"}) private Double doubleData; /** * 忽略這個字段 */ @ExcelIgnore private String ignore;
public String getString() { return string; }
public void setString(String string) { this.string = string; }
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; }
public Double getDoubleData() { return doubleData; }
public void setDoubleData(Double doubleData) { this.doubleData = doubleData; }
public String getIgnore() { return ignore; }
public void setIgnore(String ignore) { this.ignore = ignore; } } |
1 2 3 4 5 6 7 8 9 10 11 | private List<DemoData> data() { List<DemoData> list = new ArrayList<DemoData>(); for (int i = 0; i < 10; i++) { DemoData data = new DemoData(); data.setString("字符串" + i); data.setDate(new Date()); data.setDoubleData(0.56); list.add(data); } return list; } |
第一種是直接輸出到指定的文件路徑下: 1 2 3 4 5 6 7 | @RequestMapping("/test1") @LogMsg("輸出到文件路徑下") public void test1() { String fileName = "D:/RESOURCE_ROOT/CoreResrcFile/" + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data()); return ; } |
第二種是利用response在頁面上下載: 需要注意的是,第二種方式下,,是不能使用ajax進行的,,所有需要用到response的操作,ajax都不支持 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @RequestMapping("/test2") @LogMsg("頁面下載") public void goToFirm(HttpServletResponse response) throws IOException { try { List list = data(); String fileName = new String("文件名稱.xlsx".getBytes(), "ISO-8859-1"); response.addHeader("Content-Disposition", "filename=" + fileName); ServletOutputStream out = response.getOutputStream(); EasyExcelFactory.write(out,DemoData.class).sheet("文件標簽名稱").doWrite(list); } catch (Exception e) { e.printStackTrace(); } return null; } |
|