前言:初次接触,没来的及优化,凑合看吧。
1.pom文件添加依赖。
org.freemarker
freemarker
2.3.20
2.新建images和templage文件夹准备存放你的图片和模板。你也可以存放到其他地方,能找到就行。
3.模板制作。
①.打开WPS或者Office编辑word文档。我用的是WPS。
②.另存为xml文件。文件名就叫template.xml.
③.用其他编辑器打开template.xml文件。我用的是EditPlus 3。将需要注入数据的地方修改为${xxx}格式,并且记住你的字段名,如果有多条数据则添加<#list userList as user><#list>标签,userList是Map里的key。
④.编辑好之后另存为.ftl文件。这就是模板。可以存放到项目里的templage里。再往images里传一张图片。
4.创建模板生成工具类。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.utility.DateUtil;
public class WordUtils {
private static Configuration configuration = null;
//classLoader.getResource()只能获取相对路径的资源
// private static final String templateFolder = WordUtils.class.getClassLoader().getResource("template").getPath();
//class.getResource()可以获取绝对路径和相对路径
private static final String templateFolder = WordUtils.class.getResource("/template").getPath();
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
configuration.setDirectoryForTemplateLoading(new File(templateFolder));
} catch (IOException e) {
e.printStackTrace();
}
}
private WordUtils() {
throw new AssertionError();
}
public static void exportMillCertificateWord(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 + DateUtils.getDate() + ".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(); // 删除临时文件
}
}
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;
}
}
6.业务类,我直接与controller写到了一块。
@RequestMapping("/exportSellPlan")
public @ResponseBody void exportSellPlan(HttpServletRequest request, HttpServletResponse response) {
Calendar calendar = Calendar.getInstance();// 取当前日期。
String imagePath = WordUtils.class.getResource("/images").getPath()+"/image2.jpg";
//获得数据
List users = userService.getUsers();
Map map = new HashMap();
map.put("text", "我想大声告诉你,你一直在我世界里。");
map.put("userList", users);
map.put("image",this.getImageBase(imagePath));
try {
WordUtils.exportMillCertificateWord(request, response, map, "方案", "template.ftl");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获得图片的base64码
@SuppressWarnings("deprecation")
public String getImageBase(String src) {
if(src==null||src==""){
return "";
}
File file = new File(src);
if(!file.exists()) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
OK!
搞定!
启动项目,输入localhost:8080/exportSellPlan