1. 程式人生 > >freemarker匯出定製excel

freemarker匯出定製excel

之前我們導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已經好了,接下來就是程式碼

 需要的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);//呼叫匯出方法 } }

執行之後