欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

ftl模板导出excel_freemarker导出定制excel

发布时间:2023/12/20 编程问答 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。