工具类解析模板生成Excel
public class TemplateParseUtil {
/**
* 解析模板生成Excel
* @param templateDir 模板目录
* @param templateName 模板名称
* @param excelPath 生成的Excel文件路径
* @param data 数据参数
* @throws IOException
* @throws TemplateException
*/
public static void parse(String templateDir,String templateName,String excelPath,Map data) throws IOException, TemplateException {
//初始化工作
Configuration cfg = new Configuration();
//设置默认编码格式为UTF-8
cfg.setDefaultEncoding("UTF-8");
//全局数字格式
cfg.setNumberFormat("0.00");
//设置模板文件位置
cfg.setDirectoryForTemplateLoading(new File(templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
//加载模板
Template template = cfg.getTemplate(templateName,"utf-8");
OutputStreamWriter writer = null;
try{
//填充数据至Excel
writer = new OutputStreamWriter(new FileOutputStream(excelPath),"UTF-8");
template.process(data, writer);
writer.flush();
}finally{
writer.close();
}
}
/**
* 解析模板返回字节数组
* @param templateDir 模板目录
* @param templateName 模板名称
* @param data 数据参数
* @throws IOException
* @throws TemplateException
*/
public static byte[] parse(String templateDir,String templateName,Map data) throws TemplateException, IOException{
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setNumberFormat("0.00");
cfg.setDirectoryForTemplateLoading(new File(templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
Template template = cfg.getTemplate(templateName,"utf-8");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Writer out = new OutputStreamWriter(outStream,"UTF-8");
template.process(data, out);
return outStream.toByteArray();
}
/**
* 自定义模板字符串解析
* @param templateStr 模板字符串
* @param data 数据
* @return 解析后的字符串
* @throws IOException
* @throws TemplateException
*/
public static String parse(String templateStr, Map data)
throws IOException, TemplateException {
Configuration cfg = new Configuration();
cfg.setNumberFormat("#.##");
//设置装载模板
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate("myTemplate", templateStr);
cfg.setTemplateLoader(stringLoader);
//加载装载的模板
Template temp = cfg.getTemplate("myTemplate", "utf-8");
Writer out = new StringWriter();
temp.process(data, out);
return out.toString();
}
}
模板文件excel.ft
ss:ExpandedRowCount="${rsvCountList?size + 2}" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="14.25">
mocking 2018-05-17T06:23:39Z 2018-05-17T06:31:50Z 2052-10.1.0.7346 27525 13650 False False ss:ExpandedRowCount="${rsvCountList?size + 2}" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="14.25">
<#list rsvCountList as rsv>
所在市 | 大(1)型 | 大(2)型 | 中型 | 小(1)型 | 小(2)型</Data> | 合计 | |
${rsv.name!} | <#list rsv.countList as c>${c.count!} | #list>${rsv.count!} | #list>0 0 100 3 0 7 R1C8 False False
0 0 100 False False
0 0 100 False False <#list rsvCountList as rsv>
所在市 | 大(1)型 | 大(2)型 | 中型 | 小(1)型 | 小(2)型</Data> | 合计 | |
${rsv.name!} | <#list rsv.countList as c>${c.count!} | #list>${rsv.count!} | #list>0 0 100 3 0 7 R1C8 False False
0 0 100 False False
0 0 100 False False
一定要注意标红处,
ss:ExpandedRowCount="${rsvCountList?size + 2}
注:这里一定要改,因为这里设置的是excel的行数,要动态的加载数据,则行数也要跟着改变(设置的行数必须>=实际的行数,不然生成的excel会打不开),${RsvCountList?size + 6}是得到userList的大小加上原来标题格式所占的6行,${list?size}可以得到list的大小。
<#list rsvCountList as rsv>
|
${rsv.name!} | <#list rsv.countList as c>${c.count!} | #list>${rsv.count!} | #list>${rsv.name!} | <#list rsv.countList as c>${c.count!} | #list>${rsv.count!} | #list>
循环遍历 RsvCountList的标签(内部又有list遍历)
public void excelTest(HttpServletResponse response,HttpServletRequest request) throws IOException{
List
//测试Excel文件生成
Map
data.put("rsvCountList", rsvCountList);
Date now = new Date();
String filename = "/resources/TempFiles/excel"+now.getTime()+".xls";
String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
String substring = nodepath+"../../";
String path2=substring+"/resources/template";
try {
TemplateParseUtil.parse(path2, "excel.ftl", substring+filename, data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("./"+filename);
}
-------------------修改版-------------------------
service and impl
/*
* service
*/
import java.io.IOException;
import java.util.Map;
import freemarker.template.TemplateException;
public interface IFreemarkerService {
byte[] parse(String fileName, Map data) throws IOException, TemplateException;
}
/*
* serviceimpl
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Service
public class FreemarkerService implements IFreemarkerService {
@Autowired
@Qualifier("freemarkerConfig")
private FreeMarkerConfigurer freemarkerConfig;//来自org.springframework.web.servlet.view.freemarker;
@Override
public byte[] parse(String fileName, Map data) throws IOException, TemplateException {
Configuration cfg = freemarkerConfig.getConfiguration();
cfg.setDefaultEncoding("UTF-8");
cfg.setNumberFormat("0.00");
cfg.setObjectWrapper(new DefaultObjectWrapper());
//cfg.setDirectoryForTemplateLoading(new File(freemarkerConfig.));
Template template = cfg.getTemplate(fileName,"utf-8");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Writer out = new OutputStreamWriter(outStream,"UTF-8");
template.process(data, out);
return outStream.toByteArray();
}
public void parseTest(String templateName,String excelPath,Map data) throws IOException, TemplateException {
//初始化工作
Configuration cfg = freemarkerConfig.getConfiguration();
//设置默认编码格式为UTF-8
cfg.setDefaultEncoding("UTF-8");
//全局数字格式
cfg.setNumberFormat("0.00");
cfg.setDirectoryForTemplateLoading(new File("d:/tmp/template/"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
//加载模板
Template template = cfg.getTemplate(templateName,"utf-8");
OutputStreamWriter writer = null;
try{
//填充数据至Excel
writer = new OutputStreamWriter(new FileOutputStream(excelPath),"UTF-8");
template.process(data, writer);
writer.flush();
}finally{
writer.close();
}
}
}
//Spring配置文件
0
UTF-8
0.##########
yyyy-MM-dd HH:mm:ss
true
ignore
@RequestMapping(value = "hztjExcel", method = RequestMethod.GET)
public void hztjExcel(HttpServletResponse response,HttpServletRequest request,ReservoirFilterDto rsvDto) throws IOException{
List reservoirStatisticsCountList = service.ReservoirStatisticsCount(rsvDto);
Map data = new HashMap();
//将DTO对象放入excelMap中
data.put("statistics", reservoirStatisticsCountList.get(0));
Date now = new Date();
String filename = "/resources/TempFiles/hztj"+now.getTime()+".xls";
String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
String substring = nodepath+"../../";
String path2=substring+"/resources/template";
OutputStream outputStream = null;
try {
//TemplateParseUtil.parse(path2, "jszbtj.ftl", substring+filename, data);
byte[] content = freemarkerService.parse("jszbtj.ftl",data);
response.setContentType("application/octet-stream;charset=UTF-8");
String userAgent = request.getHeader("user-agent").toLowerCase();
if(userAgent != null &&((userAgent.indexOf("msie")!=-1) || (userAgent.indexOf("rv") != -1 && userAgent.indexOf("firefox") == -1))
&& ((userAgent.indexOf("msie") != -1 ||(userAgent.indexOf("rv")!=-1 && userAgent.indexOf("chrom") == -1)))){
//识别IE浏览器
filename = URLEncoder.encode(filename, "UTF-8");
} else {
//非IE浏览器
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.addHeader("Content-Length", String.valueOf(content.length));
outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(content);
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//response.sendRedirect("../"+filename);
}
导出其它格式文件参考https://blog.csdn.net/u010722643/article/details/41732607