1.导入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2.设置模板
2.1 把需要替换的内容更改为${…}的格式
2.2 把模板另存为xml格式
2.3 把xml文件放进项目的templates文件夹下,把后缀名改为ftl
2.4 格式转换之后可能会出现占位符错乱的情况,检查一遍自己定义的占位符。如果格式不对,就更改回来${…}的格式
3.编写工具类
import org.slf4j.Logger;
import com.sun.deploy.net.URLEncoder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
/**
* @author YCX
* @Title: ExportWord
* @date 2020年11月03日 14:21:00
*/
public class ExportWord {
private static Logger logger = LoggerFactory.getLogger(ExportWord.class);
private Configuration configuration;
private String encoding;
private String exportPath = "C:/demo/word/";
/**
* 构造函数
* 配置模板路径
* @param encoding
*/
public ExportWord(String encoding) {
this.encoding = encoding;
configuration = new Configuration();
configuration.setDefaultEncoding(encoding);
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
}
/**
* 获取模板
* @param name
* @return
* @throws Exception
*/
public Template getTemplate(String name) throws Exception {
return configuration.getTemplate(name);
}
/**
* 导出word文档到指定目录
* @param fileName
* @param tplName
* @param data
* @throws Exception
*/
public void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {
logger.debug("导出word到C:/demo/word/");
//如果目录不存在,则创建目录
File exportDirs = new File(exportPath);
if (!exportDirs.exists()) {
exportDirs.mkdirs();
}
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));
getTemplate(tplName).process(data, writer);
}
/**
* 导出word文档到客户端
*
* @param response
* @param fileName
* @param tplName
* @param data
* @throws Exception
*/
public void exportDoc(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 把本地文件发送给客户端
Writer out = response.getWriter();
Template template = getTemplate(tplName);
template.process(data, out);
}
/**
* @param src 图片路径
* @return 图片的编码
* @throws Exception
*/
public String getImageBase(String src) throws Exception {
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);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
// public static void main(String[] args) throws Exception {
// ExportWord exportWord = new ExportWord("UTF-8");
// System.out.println(exportWord.getImageBase("C:\\Users\\YCX\\Pictures\\Saved Pictures\\90.jpg"));
// }
}
4.写controller,调用工具类的方法
import com.zhikuan.entity.Cai;
import com.zhikuan.util.ExportWord;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.CachedRowSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* @author YCX
* @Title: ExportDocController
* @date 2020年11月03日 14:28:00
*/
@Controller
@RequestMapping("/export")
public class ExportDocController {
@RequestMapping("/exportWord")
public void exportWord(HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName = "本周菜谱.doc"; //文件名称
ArrayList<Cai> cais = new ArrayList<>();
cais.add(new Cai("早餐","小米粥","烧饼","油条","韭菜盒","水饺","蒸饺","饭团"));
cais.add(new Cai("午餐","稀饭","白饭","油饭","蛋炒饭","地瓜粥","卤肉饭","馄饨面"));
cais.add(new Cai("晚餐","刀削面","麻辣面","长寿桃","麻花","麻酱面","鴨肉面","鱔魚面"));
cais.add(new Cai("加餐","炒米粉","冬粉","鱼丸汤","貢丸汤","蛋花汤","蛤蜊汤","花枝羹"));
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("caiList", cais);
ExportWord exportWord = new ExportWord("UTF-8");
//这里写 要导出图片的路径
String imageBase = exportWord.getImageBase("C:\\Users\\YCX\\Pictures\\Saved Pictures\\90.jpg");
dataMap.put("img",imageBase);
exportWord.exportDoc(response, fileName, "caipu2.ftl", dataMap);
}
@RequestMapping("/goWord")
public String goWord(Model model) throws Exception {
ArrayList<Cai> cais = new ArrayList<>();
cais.add(new Cai("早餐","小米粥","烧饼","油条","韭菜盒","水饺","蒸饺","饭团"));
cais.add(new Cai("午餐","稀饭","白饭","油饭","蛋炒饭","地瓜粥","卤肉饭","馄饨面"));
cais.add(new Cai("晚餐","刀削面","麻辣面","长寿桃","麻花","麻酱面","鴨肉面","鱔魚面"));
cais.add(new Cai("加餐","炒米粉","冬粉","鱼丸汤","貢丸汤","蛋花汤","蛤蜊汤","花枝羹"));
model.addAttribute("caiList",cais);
return "caiPu";
}
@Test
public void test01() throws Exception {
String fileName = "本周菜谱.doc"; //文件名称
ArrayList<Cai> cais = new ArrayList<>();
cais.add(new Cai("早餐","小米粥","烧饼","油条","韭菜盒","水饺","蒸饺","饭团"));
cais.add(new Cai("午餐","稀饭","白饭","油饭","蛋炒饭","地瓜粥","卤肉饭","馄饨面"));
cais.add(new Cai("晚餐","刀削面","麻辣面","长寿桃","麻花","麻酱面","鴨肉面","鱔魚面"));
cais.add(new Cai("加餐","炒米粉","冬粉","鱼丸汤","貢丸汤","蛋花汤","蛤蜊汤","花枝羹"));
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("caiList", cais);
ExportWord exportWord = new ExportWord("UTF-8");
exportWord.exportDocFile(fileName,"caipu2.ftl", dataMap);
}
public static void main(String[] args) throws Exception {
String fileName = "本周菜谱.doc"; //文件名称
Map<String, Object> dataMap = new HashMap<>();
ExportWord exportWord = new ExportWord("UTF-8");
dataMap.put("z", "早餐");
dataMap.put("z1", "小米粥");
dataMap.put("z2", "小米粥");
dataMap.put("z3", "小米粥");
dataMap.put("z4", "小米粥");
dataMap.put("z5", "小米粥");
dataMap.put("z6", "小米粥");
dataMap.put("z7", "小米粥");
dataMap.put("x", "午餐");
dataMap.put("x1", "面条");
dataMap.put("x2", "面条");
dataMap.put("x3", "面条");
dataMap.put("x4", "面条");
dataMap.put("x5", "面条");
dataMap.put("x6", "面条");
dataMap.put("x7", "面条");
dataMap.put("c", "晚餐");
dataMap.put("c1", "米饭");
dataMap.put("c2", "米饭");
dataMap.put("c3", "米饭");
dataMap.put("c4", "米饭");
dataMap.put("c5", "米饭");
dataMap.put("c6", "米饭");
dataMap.put("c7", "米饭");
dataMap.put("v", "加餐");
dataMap.put("v1", "包子");
dataMap.put("v2", "包子");
dataMap.put("v3", "包子");
dataMap.put("v4", "包子");
dataMap.put("v5", "包子");
dataMap.put("v6", "包子");
dataMap.put("v7", "包子");
exportWord.exportDocFile(fileName, "caipu.ftl", dataMap);
}
}
5.注意事项:
5.1模板里的${…}里面的内容,在传递的map里面必须要有,没有的话会报错
5.2导出图片:与设置普通参数一样模板里有${xxx},设置map的时候就map.put(“xxx”,“xxx”);需要注意的是:给图片设置的值是图片内容的64进制编码值
获取图片的编码值
//获取图片的编码值
public String getImageBase(String src) throws Exception {
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);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
给图片占位符设置值
String imageBase = exportWord.getImageBase("C:\\Users\\YCX\\Pictures\\Saved Pictures\\90.jpg");
dataMap.put("img",imageBase);