excel导出工具类配合excel模板使用
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @Author:cwh
* @Date: 2020/12/24 11:45
*/
@Slf4j
public class ExportUtils {
/**
* 导出excle数据
* @param fileName 下载文件名
* @param templateName 模板文件名
* @param dataMap 导出数据
* @param response
*/
public static void export(String fileName, String templateName,Map<String, Object> dataMap, HttpServletResponse response){
//获取临时保存文件目录
String upfilePath = System.getProperty("java.io.tmpdir").concat("/smartcity/excel/");
File upfilePathFile = new File(upfilePath);
if (!upfilePathFile.exists()){
upfilePathFile.mkdirs();
}
String filePathName = upfilePath.concat(fileName);
File outFile = new File(filePathName);
try (
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile), Charset.forName(StandardCharsets.UTF_8.name())));// 此处为输
// 从response对象中得到输出流,准备下载
OutputStream myout = response.getOutputStream();
// 读出文件到i/o流
FileInputStream fis = new FileInputStream(outFile);
BufferedInputStream buf = new BufferedInputStream(fis);
){
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
// ftl模板文件
configuration.setClassForTemplateLoading(ExportUtils.class, "/templates/");
Template template = configuration.getTemplate(templateName);
template.process(dataMap, writer);
writer.flush();
// 设置response的编码方式
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
// 相当于我们的缓存
byte[] b = new byte[1024];
// 该值用于计算当前实际下载了多少字节
long k = 0;
// 开始循环下载
while (k < outFile.length()) {
int j = buf.read(b, 0, 1024);
k += j;
// 将b中的数据写到客户端的内存
myout.write(b, 0, j);
}
// 将写入到客户端的内存的数据,刷新到磁盘
myout.flush();
} catch (Exception e) {
log.error("导出EXCEL异常", e);
throw new RuntimeException("导出EXCEL异常");
}
}
}