
正文
java用freemarker实现导出excel
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
前几天做了jxl导出excel,现在用freemarker做一下
freemarker导出excel和导出word步骤和是实现方法是相同的。
1.制作excel模板
2.将后缀名改为ftl,放到对应的位置下
3.实现方法
package org.lq.ssm.gp.controller; import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.lq.ssm.entity.LandUser;
import org.springframework.web.bind.annotation.RequestMapping; import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler; public class exportExcel { private Configuration configuration = null; public exportExcel(){
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
//@RequestMapping(params="print")
public void print() throws IOException { configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
// 要填入模本的数据文件
Map dataMap = new HashMap();
//getData(dataMap); List<Map<String, Object>>list=new ArrayList<Map<String,Object>>();
for(int i=0;i<10;i++){
Map<String, Object>map=new HashMap<String, Object>();
map.put("userName", "张三");
map.put("landName", "张三");
map.put("landScmj", "111111");
map.put("landBzdate", "20170626");
list.add(map);
}
dataMap.put("list", list); // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
// 这里我们的模板
//configuration.setDirectoryForTemplateLoading(new File("G:\\")); configuration.setClassForTemplateLoading(this.getClass(), "/org/lq/ssm/gp/controller");
//设置异常处理器
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
Template t = null;
try {
// test.ftl为要装载的模板
t = configuration.getTemplate("land.ftl");
t.setEncoding("utf-8"); } catch (IOException e) {
e.printStackTrace();
}
// 输出文档路径及名称
File outFile = new File("G:/TTT/land.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();
}
} /**
* 注意dataMap里存放的数据Key值要与模板中的参数相对应
* @param dataMap
* @throws IOException
*
*/ public static void main(String[] args) throws IOException { exportExcel exc=new exportExcel();
exc.print();
} }
4.excel表格就好了。但是可能在打开文件的时候,出现错误。
这时候修改模板内容,找到
将值改大一点,就可以了。





