ftl模板导出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復制到項目的resource目錄中將后綴名改為.ftl
到這一步excel已經好了,接下來就是代碼
需要的maven包
org.freemarker
freemarker
2.3.20
導出的方法
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 classFreemarkerWord {private Configuration configuration = null;publicFreemarkerWord() {
configuration= newConfiguration();
configuration.setDefaultEncoding("utf-8");
}/**
* dataMap為要裝載的數據
* @param dataMap*/
public voidcreateDoc(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");
Writerout = null;try{out = new BufferedWriter(newOutputStreamWriter(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 voidmain(String[] args) {
Map map=newHashMap();
map.put("id", "1");//添加數據
map.put("name", "光頭權");
FreemarkerWord fw=newFreemarkerWord();
fw.createDoc(map);//調用導出方法
}
}
運行之后
再就是導出多條數據,修改之后的可循環遍歷數據
查詢數據庫后調用導出方法,數據也能正常導出
/**
* 根據excel模板導出數據*/@RequestMapping("listAll")
@ResponseBodypublic voidlistAll() {
PageData pd=this.getPageData();//用于接受參數的封裝類
FreemarkerWord fw=new FreemarkerWord();//實例化該導出類
Map dataMap = newHashMap();try{
List 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
總結
以上是生活随笔為你收集整理的ftl模板导出excel_freemarker导出定制excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vbs脚本学习笔记
- 下一篇: 【转载】听说树莓派性能差,什么最好别尝试