1. 程式人生 > >java用freemarker實現導出excel

java用freemarker實現導出excel

pla tro tac template src odin cnblogs data ioe

前幾天做了jxl導出excel,現在用freemarker做一下

freemarker導出excel和導出word步驟和是實現方法是相同的。

1.制作excel模板

2.將後綴名改為ftl,放到對應的位置下

3.實現方法

  1 package org.lq.ssm.gp.controller;
  2 
  3 import java.io.BufferedWriter;
  4 import java.io.File;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.OutputStreamWriter;
8 import java.io.Writer; 9 import java.util.ArrayList; 10 import java.util.HashMap; 11 import java.util.List; 12 import java.util.Map; 13 14 import org.lq.ssm.entity.LandUser; 15 import org.springframework.web.bind.annotation.RequestMapping; 16 17 import freemarker.template.Configuration;
18 import freemarker.template.Template; 19 import freemarker.template.TemplateException; 20 import freemarker.template.TemplateExceptionHandler; 21 22 public class exportExcel { 23 24 private Configuration configuration = null; 25 26 public exportExcel(){ 27 configuration = new
Configuration(); 28 configuration.setDefaultEncoding("utf-8"); 29 } 30 //@RequestMapping(params="print") 31 public void print() throws IOException { 32 33 configuration = new Configuration(); 34 configuration.setDefaultEncoding("utf-8"); 35 // 要填入模本的數據文件 36 Map dataMap = new HashMap(); 37 //getData(dataMap); 38 39 List<Map<String, Object>>list=new ArrayList<Map<String,Object>>(); 40 for(int i=0;i<10;i++){ 41 Map<String, Object>map=new HashMap<String, Object>(); 42 map.put("userName", "張三"); 43 map.put("landName", "張三"); 44 map.put("landScmj", "111111"); 45 map.put("landBzdate", "20170626"); 46 list.add(map); 47 } 48 dataMap.put("list", list); 49 50 // 設置模本裝置方法和路徑,FreeMarker支持多種模板裝載方法。可以重servlet,classpath,數據庫裝載, 51 // 這裏我們的模板 52 //configuration.setDirectoryForTemplateLoading(new File("G:\\")); 53 54 55 configuration.setClassForTemplateLoading(this.getClass(), "/org/lq/ssm/gp/controller"); 56 //設置異常處理器 57 configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); 58 Template t = null; 59 try { 60 // test.ftl為要裝載的模板 61 t = configuration.getTemplate("land.ftl"); 62 t.setEncoding("utf-8"); 63 64 } catch (IOException e) { 65 e.printStackTrace(); 66 } 67 // 輸出文檔路徑及名稱 68 File outFile = new File("G:/TTT/land.xls"); 69 Writer out = null; 70 71 try { 72 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); 73 } catch (Exception e1) { 74 e1.printStackTrace(); 75 } 76 77 try { 78 t.process(dataMap, out); 79 out.close(); 80 } catch (TemplateException e) { 81 e.printStackTrace(); 82 } catch (IOException e) { 83 e.printStackTrace(); 84 } 85 } 86 87 88 89 /** 90 * 註意dataMap裏存放的數據Key值要與模板中的參數相對應 91 * @param dataMap 92 * @throws IOException 93 * 94 */ 95 96 public static void main(String[] args) throws IOException { 97 98 exportExcel exc=new exportExcel(); 99 exc.print(); 100 } 101 102 }

4.excel表格就好了。但是可能在打開文件的時候,出現錯誤。

這時候修改模板內容,找到技術分享

將值改大一點,就可以了。

技術分享

java用freemarker實現導出excel