最近项目中要使用到导出word这项功能,参考了许多导出的方法,发现使用freemarker模板导出word的效果最好可以保持原样。
导入freemarker的架包
1.首先我们需要用word制作一份模板,打开word编辑我们想要的word样式。
如图:
2.在需要填写的地方用变量来代替。如果有图片需要先用图片来填充。然后另存为xml文件,然后再把后缀名改为.ftl的格式
3.处理ftl文件,把图片替换成变量。
4.word表格的填充,ftl也要做修改。找到自己表格所在的那行,word中<w:tr>表示一行,我们找到表头的下一行。
从这行开始修改studengList表示待会代码要放进去的List <w:tr>,缩起来了
5.java代码
package com.smxy.lq.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;
/**
*
* @Description :使用freemark模板生成word文档
* @author Bush罗
* @date 2018年8月20日
*
*/
public class WordFreemark {
private Configuration configuration = null;
public WordFreemark() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public static void main(String[] args) {
WordFreemark test = new WordFreemark();
test.createWord();
}
public void createWord() {
Map<String, Object> dataMap = new HashMap<String, Object>();
getData(dataMap);
configuration.setDefaultEncoding("utf-8");//设置编码
configuration.setClassicCompatible(true);
configuration.setClassForTemplateLoading(
this.getClass(),
"/ftl/word");// FTL文件所存在的位置
Template t = null;
try {
t = configuration.getTemplate("word.ftl"); // ftl模板名称
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("D:/word" + Math.random() * 10000
+ ".doc");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getData(Map<String, Object> dataMap) {
dataMap.put("name", "Bush罗");
dataMap.put("number", "2015089879");
//填充图片
dataMap.put("image", getImageStr());
//表格填充
List<Student> studentList=new ArrayList<Student>();;
for(int i=0;i<10;i++){
Student student=new Student();
student.setName("小明");
student.setPhone("1234567");
student.setSex("男");
studentList.add(student);
}
dataMap.put("studentList", studentList);
}
//图片转码
public String getImageStr() {
String imgFile = "E:/AAA.png";
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}
6.生成样式