實習第二周 NO.2 Plus
項目組長剛把以前的excel模板發給我的時候,看得我是目瞪口呆,一度以為那是一種我不懂得新的語言。后來才知道它是這么個東東
“ExcelUtils代表著一類的報表生成工具,他使用報表本身作為模板。對于它,只能處理Excel文件,它以Excel文件為模板,在其上加以自己的定義語言,簡單通俗!”
ExcelUtils官網
使用起來也很簡單,就是先在excel的表格里寫好自己的excelutils模板,然后準備好要傳入的數據集合,最后通過export()方法實現生成導出就好啦。
定義excel模版(在excel中使用自定義標簽)
1.遍歷list(迭代輸出list中數據)
#foreach detail in ${list}
${detail.name} ${detail.qty} ...
#end
在#foreach和#end之間獲取detail對象的屬性,還有以下幾種特殊的變量:
${detailId}——list的索引
${detailIndex}——序號
${detailStartRowNo}——遍歷時開始行號
${detailEndRowNo}——遍歷結束行號
2.獲取變量的值
${printDate}
${model.name}
${map(key)}——獲取value
其中${!model.name}:如果該值和上一個數值相同,則合并該單元格;可以取某一個年份的,自動合并該單元格
3.取和(針對某一列)
#formula SUM(C${detailStartRowNo}:C${detailEndRowNo})
4.取和(針對某一行)
#formula SUM(C${currentRowNo}:F${currentRowNo})
5.遍歷對象的所有屬性(兼容poi高版本導致#each標簽失效)
#each ${model}
6.遍歷對象符合條件的屬性,${width1}代表合并幾個單元格
#each ${model} on ${keys}
#each ${model} ${width1},${width2}... on ${keys}
7.If標簽
①#if (${a.tranType}=="201" || ${a.tranType}=="203")
#end
②#formula IF(${sex}=1,"男","女")需注意sex字段為數值類型
8.根據條件統計數值
#sum qty on ${list} where name=test
#sum qty on ${list} where name like test
#sum qty on ${list} where name like ${value}
9.調某一個方法
#call service.getStr("str",${aaa})
#call service.getModel("str",${aaa}).name
Java代碼導出示例
public String prExport() throws Exception {
try {
/數據處理部分start/
Person person = this.personService.search(appDis.getPersonId());
/數據處理部分end/
/工具 start/
ExcelUtils.addValue("exportDate", DateUtil.getNowDate("yyyy年M月d日"));
ExcelUtils.addValue("person", person);
/工具 end/
String path = ServletActionContext.getServletContext().getRealPath("WEB-INF");
String config = path+"\xls\prAppDis.xls";//已定義好的模板
String fileName = "聘用合同辦理備案表"+System.currentTimeMillis()+".xls";
File file = new File(Resource.PATH+"\d_rs_app_dis");
if(!file.exists() && !file.isDirectory()){
System.out.println("http://不存在");
file.mkdirs();
}else{
System.out.println("http://目錄存在");
}
File exportFile = new File(Resource.PATH+"\d_rs_app_dis",fileName);
if(!exportFile.exists()){
exportFile.createNewFile();
}
FileOutputStream fo = new FileOutputStream(exportFile);
ExcelUtils.export(config, fo);
fo.close();
/至此文件已導出成功/
} catch (Exception e) {
LogUtil.exception(e);
status = e.getMessage();
}
return SUCCESS;
}
導出報表
public String exporCountPerson() throws Exception{
//這個方法就是使用POI動態生成excel的模板,里面已經拼好了ExcelUtils的標簽,參數就是要拼接到表頭以及數據信息
trStatisticsService.exportTrstatistics(headList,headerList,dicList);
//給excel模板中的標簽list賦值
ExcelUtils.addValue("list", this.mapList);
//使用ExcelUtils輸出文件
String path = ServletActionContext.getServletContext().getRealPath("");
String config = path + "\\template\\trstatisticsNum.xls";
File file = new File(path, "trstatisticsNum.xls");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
ExcelUtils.export(config, fo);
fo.close();
this.excelFile = new FileInputStream(file);
this.downloadFileName = new String("各單位各類培訓持證人數匯總報表.xls".getBytes(), "ISO8859-1");
return "exportExcel";
}