1.概況
背景:SSM框架下的maven管理項目
需求:將datagrid前端展示的表格導出爲Excel文件
插件:easypoi(現成的輪子)
備註:此方法只要引入插件,並且有獲取datagrid的數據源方法就足夠完成了,導出的樣式是單sheet非模板的Excel表格。
2.實現
整體思路:
1.引入插件jar包
2.前臺頁面添加導出按鈕和點擊事件
3.後臺導出處理:
1)兩個List,一個是你的datagrid數據源,一個是與數據源對應,用於導出設置的泛型ExcelExportEntity的List
2)進行各種設置後就可以導出啦!
1)pom.xml文件引入easypoi依賴
<!-- easyPoi -->
<dependency>
<groupId>org.jeecg</groupId>
<artifactId>easypoi-base</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.jeecg</groupId>
<artifactId>easypoi-web</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.jeecg</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>2.4.0</version>
</dependency>
2)前臺頁面添加導出表格按鈕和按鈕點擊事件
按鈕:
<a id='export'>導出表格</a>
事件:
$('#export').on('click',function(){
if($('#dg').datagrid('getData').total == 0){
return;
}else{
window.location='<%=basePath%>export/exportExcel';
}
});
其中dg是要導出的datagrid的id,window.location後面跟的是導出表格的controller訪問地址。
3)編寫後臺controller
@RequestMapping("/exportExcel")
public String dataExport(ModelMap modelMap) {
try {
List<ExcelExportEntity> entityList = new ArrayList<ExcelExportEntity>();
entityList.add(new ExcelExportEntity("列1", "column1",40));//參數依次爲(excel列名,結果集list的map主鍵,excel單元格寬度)
entityList.add(new ExcelExportEntity("列2", "column2",25));
entityList.add(new ExcelExportEntity("列3", "column3",25));
entityList.add(new ExcelExportEntity("列4", "column4",25));
entityList.add(new ExcelExportEntity("列5", "column5",25));
List<Map<String, Object>> dataResult = (獲取你datagrid數據的方法)
modelMap.put(MapExcelConstants.ENTITY_LIST, entityList);//放入你的excel列表設置
modelMap.put(MapExcelConstants.MAP_LIST, dataResult);//放入你的datagrid數據結果列表
modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("我是文件標題",""));
modelMap.put(MapExcelConstants.FILE_NAME, "我是文件名",""));
return MapExcelConstants.JEECG_MAP_EXCEL_VIEW;
}catch(Exception e) {
this.logger.error(e.getMessage());
}
return NormalExcelConstants.JEECG_EXCEL_VIEW;
}
將表格內容導出,實際上是再次請求表格查詢的方法,並把結果集導出;
上面用到兩個列表:entityList和dataResult,entityList用的都是easypoi封裝好的方法,主要是對導出後excel的列設置;dataResult是你的表格結果集,字段要與entityList設置的column1,column2...對應。
最終導出結果如圖~
3.碎碎念
每次接觸到沒做過的模塊都免不了頭大,到處搜資料導出碰釘子哈,但往往實現後才發現根本不是這麼複雜呀hhhh,做這個模塊的時候我先引入的poi的依賴,又引入了easypoi的依賴,結果jar包衝突解決了半天...引入easypoi就已經包括poi的包了,畢竟是現成的輪子了,不過做之前我確實沒這個概念?
多sheet模板導出可以參考我的這篇文章:poi實現列表導出多sheet模板excel文件