package com.chen.springmvc.util;
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.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class WordUtil {
private Configuration configuration = null;
public WordUtil(){
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
//dataMap 要填入模本的数据文件
public void createDoc(Map<String,Object> dataMap,String fileName) {
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
System.out.println(WordUtil.class.getClassLoader().getResource("/template/"));
configuration.setClassForTemplateLoading(WordUtil.class, "/template/");
Template t=null;
try {
//test.ftl为要装载的模板
t = configuration.getTemplate("fctestpaper.ftl");
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException | UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*public String getImageStr(String imgFile){
InputStream in=null;
byte[] data=null;
try {
in=new FileInputStream(imgFile);
data=new byte[in.available()];
in.read(data);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder=new BASE64Encoder();
return encoder.encode(data);
}*/
}
最近下载更多
xiaobaitud LV13
2022年9月19日
EdgarLi LV14
2020年11月17日
maojianyun LV30
2020年7月27日
三几个 LV11
2020年4月9日
libo1212 LV8
2020年1月17日
815447208 LV6
2019年12月20日
单随心 LV4
2019年8月2日
644106 LV8
2019年7月5日
WGM_LW LV5
2019年6月27日
野野打野 LV1
2019年6月11日
最近浏览更多
qiheideguang LV18
4月10日
3334004690 LV11
2024年6月24日
liu2022 LV14
2024年4月29日
467277 LV13
2024年3月26日
AliceL LV1
2023年5月14日
xiaobaitud LV13
2022年9月19日
yang The LV1
2022年9月2日
最代码-彭小康
2022年7月6日
暂无贡献等级
为我所用 LV1
2022年6月21日
pfb123456 LV8
2022年6月16日

