之前我們導excel大部分用的是jxl和poi,JXL只能對Excel進行操作,屬於比較老的框架,它只支持到Excel 95-2000的版本。現在已經停止更新和維護
POI是apache的項目,可對微軟的Word,Excel,ppt等進行操作,包括office2003和2007,Excl2003和2007。poi現在一直有更新。所以現在主流使用POI
如果只是簡單的excel,用上述工具導出沒有任何問題,但如果導出定制化復雜的excel或word,就會顯得很繁瑣,代碼也有一定難度,所以我嘗試用freemarker
來導出
先制作一個定制的excel
新建一個excel,在里面寫上點數據並將后綴改為.xml
將下圖的 1和張三改一下以接收數據,將excel復制到項目的resource目錄中將后綴名改為.ftl
到這一步excel已經好了,接下來就是代碼
需要的maven包
<!--word;excel導出包--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency>
導出的方法
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