以前咱們導excel大部分用的是jxl和poi,JXL只能對Excel進行操做,屬於比較老的框架,它只支持到Excel 95-2000的版本。如今已經中止更新和維護java
POI是apache的項目,可對微軟的Word,Excel,ppt等進行操做,包括office2003和2007,Excl2003和2007。poi如今一直有更新。因此如今主流使用POI數據庫
若是隻是簡單的excel,用上述工具導出沒有任何問題,但若是導出定製化複雜的excel或word,就會顯得很繁瑣,代碼也有必定難度,因此我嘗試用freemarkerapache
來導出app
先製做一個定製的excel框架
新建一個excel,在裏面寫上點數據並將後綴改成.xmlmaven
將下圖的 1和張三改一下以接收數據,將excel複製到項目的resource目錄中將後綴名改成.ftl工具
到這一步excel已經好了,接下來就是代碼this
須要的maven包spa
<!--word;excel導出包--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency>
導出的方法.net
package com.pskj.GSLZ.utils.word; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; import java.util.HashMap; import java.util.Map; /** * word,excel導出 */ public class FreemarkerWord { private Configuration configuration = null; public FreemarkerWord() { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); } /** * dataMap爲要裝載的數據 * @param dataMap */ public void createDoc(Map dataMap) { // 設置模本裝置方法和路徑,FreeMarker支持多種模板裝載方法。能夠重servlet,classpath,數據庫裝載, // 這裏個人模板是放在resources/ftl包下(放在其它位置總會報文件找不到) configuration.setClassForTemplateLoading(this.getClass(), "/ftl"); Template t = null; try { // test2.ftl爲要裝載的模板 t = configuration.getTemplate("test2.ftl"); t.setEncoding("utf-8"); } catch (IOException e) { e.printStackTrace(); } // 輸出文檔路徑及名稱 File outFile = new File("E:/test2.xls"); Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "utf-8")); } catch (Exception e1) { e1.printStackTrace(); } try { t.process(dataMap, out); out.close(); } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Map map=new HashMap(); map.put("id", "1");//添加數據 map.put("name", "光頭權"); FreemarkerWord fw=new FreemarkerWord(); fw.createDoc(map);//調用導出方法 } }
運行以後
再就是導出多條數據,修改以後的可循環遍歷數據
查詢數據庫後調用導出方法,數據也能正常導出
/** * 根據excel模板導出數據 */ @RequestMapping("listAll") @ResponseBody public void listAll() { PageData pd=this.getPageData();//用於接受參數的封裝類 FreemarkerWord fw=new FreemarkerWord();//實例化該導出類 Map dataMap = new HashMap(); try{ List<Map> list=fhlogService.listAll(pd);//獲取多組數據 dataMap.put("list",list);//將數據裝進Map fw.createDoc(dataMap);//調用導出方法 }catch (Exception e){ e.printStackTrace(); } }
參考連接: https://blog.csdn.net/guangcigeyun/article/details/78769704
參考連接: https://www.jianshu.com/p/66645b71942f