准备ftl模板
先创建word文档,然后保存成ftl文件,找到需要填充的关键字,用KaTeX parse error: Expected 'EOF', got '#' at position 15: {key}替换,列表可得用<#̲list key as map…{map.key}。就相当于一个大Map里存有String和List
工具类
package com.bj.aisino.afx.utils;
import com.aisino.aosplus.core.Constants;
import com.aisino.aosplus.core.util.Guid;
import com.bj.aisino.afx.declare.ReportAnalysis;
import com.sun.deploy.net.URLEncoder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.log4j.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
public class WordUtils {
static Logger logger = Logger.getLogger(WordUtils.class);
//配置信息,代码本身写的还是很可读的,就不过多注解了
private static Configuration configuration = null;
//这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
private static final String templateFolder = WordUtils.class.getClassLoader().getResource("").getPath();
//private static final String templateFolder = "H:/我的项目/lm/lm/web/src/main/webapp/WEB-INF/templates";
static {
// configuration = new Configuration();
configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding("utf-8");
try {
configuration.setDirectoryForTemplateLoading(new File(templateFolder));
} catch (IOException e) {
e.printStackTrace();
}
}
private WordUtils() {
throw new AssertionError();
}
public static String exportMillCertificateWord(Map map, String title, String ftlFile) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
FileOutputStream out = null;
String filePath = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map,freemarkerTemplate);
fin = new FileInputStream(file);
String fileName = title + Guid.g() + ".doc";
filePath = Constants.WEBAPP_PATH +"/www/upload/" +fileName;
File file2 = new File(filePath);
if (!file2.exists()) {
file2.createNewFile();
}
out = new FileOutputStream(file2);
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到指定文件中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
}catch (Exception e){
logger.error("======文件生成失败,原因:{}",e);
} finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
}
return filePath;
}
private static File createDoc(Map<?, ?> dataMap, Template template) {
String name = "sellPlan.doc";
File f = new File(name);
Template t = template;
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
public static void exportMillCertificateWordPro(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map,freemarkerTemplate);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
String fileName = title + ".doc";
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
}
}
}
我主要是用exportMillCertificateWord方法生成word文档,返回生成的word路径,因为我们封装了方法根据路径下载文件,做这个的时候主要是模板不会弄,工具类不就是拿来看看代码就能用了吗?所以我把模板制作放到了前面,希望对你有帮助。