一、简介
通过freemarker生成work文档,其实原理很简单,先生成一个work的xm模板,然后替换文档中的内容为自己需要的内容就可以了。二、生成work文档
1、生成ftl模板把自己要修改的work模板另存为xml格式,然后替换其中的响应内容为ftl标签的EL形式,例如 ${image},机械试操作就不多说了
2、maven配置
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
3、示例程序
import sun.misc.BASE64Encoder;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class CreateDocWithImage {
private Configuration configuration = null;
/**
* 初始化配置
*/
public CreateDocWithImage() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
/**
* 根据模板和数据生成word放到out中
*/
public void create(OutputStream out) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", getImageStr());//ftl标签为:${image}
configuration.setDirectoryForTemplateLoading(new File("docTemplate"));
Template t = configuration.getTemplate("doc2.ftl");
Writer writer = new BufferedWriter(new OutputStreamWriter(out));
t.process(map, writer);
writer.close();
}
/**
* 获取图片数据
*/
private String getImageStr() {
String imgFile = "images/test.jpg";
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
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 {
File outFile = new File("D:/outFile.doc");
FileOutputStream out = new FileOutputStream(outFile);
new CreateDocWithImage().create(out);
out.flush();
out.close();
}
}
4、输出流转换为输入流
freemarker生成的数据流为输出流,但是在web应用程序中生成的work文档下载,一般都需要一个输入流,可通过ByteArrayOutputStream和ByteArrayInputStream进行转换。
// 把生成的数据放到输入流
ByteArrayOutputStream bout = new ByteArrayOutputStream();
new CreateDocWithImage().create(bout);
byte[] data = bout.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(data);
byte[] b = new byte[1024];
in.read(b, 0, 100);
for(int i=0;i<100;i++){
System.out.println(b);
}
bout.flush();
bout.close();