第一步就是将World文档里面需要从数据库填充的部分用占位符替换
第二步:就是将此文档保存为Xml格式(下图给出的是另存为XML文件(*.xml)格式,一般导出2013版本的可以避免乱码)
第三步:将其放在resources下并将后缀改为.ftl
第四步:需要导入freemarker相关jar包
<!-- freemarker开始 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- freemarker结束 -->
第五步:开始写java代码,首先写一个工具类
package cn.com.goldwind.ercp.fas.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;
/**
* 写入word工具类
*/
public class TempleWordUtil {
private static Configuration configuration = null;
public static Configuration getConfigurationInstance(String basePackagePath){
if(configuration == null){
configuration = new Configuration(Configuration.VERSION_2_3_0);
configuration.setDefaultEncoding("UTF-8");
configuration.setLocale(Locale.CHINA);
configuration.setEncoding(Locale.CHINA, "UTF-8");
configuration.setClassForTemplateLoading(TempleWordUtil.class,basePackagePath);
}
return configuration;
}
/**
* 导出word文件
*
*/
public static void createWord(Map<String, Object> variables,String ftlName, String fileName, HttpServletResponse response) throws Exception{
File outFile = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
Writer out = null;
try {
//定义文件后缀
fileName = fileName + ".doc";
//获取模板文件
Template t = TempleWordUtil.getConfigurationInstance("/print-templates/supervise/").getTemplate(ftlName);//获取模板文件
//将填充数据填入模板文件并输出到目标文件
String outFilePath = new File("").getCanonicalPath()+File.separator;
outFile = new File(outFilePath+fileName); //导出文件
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
t.process(variables,out);
//获取输出临时文件流
int bytesRead;
byte[] buff = new byte[2048];
bis = new BufferedInputStream(new FileInputStream(outFile));
//输出参数设定
response.setHeader("Content-Length", String.valueOf(outFile.length()));
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
response.setContentType("application/msword");
//文件输出
bos = new BufferedOutputStream(response.getOutputStream());
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
System.out.println("word导出出错。。。");
e.printStackTrace();
}finally {
try {
if (bis != null) {
out.close();
bis.close();
bos.close();
}
if (bos != null) {
bos.close();
}
//回收过渡文件
if(outFile.exists()){
outFile.delete();
}
} catch (IOException e) {
System.out.println("word导出出错。。。");
e.printStackTrace();
}
}
}
}
/**
* 模板导出
* @param uuid
*/
@RequestMapping("/exportword/{uuid}")
private void generateWord(@PathVariable String uuid) {
try {
/*数据设定*/
Map<String, Object> params = encapMap(uuid);
/*生成word并提供下载*/
TempleWordUtil.createWord(params,"qualityweekly.ftl","基础质量周报",response);
//qualityweekly.ftl为模板的位置,基础质量周报为导出World的位置
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 封装导出数据
* @param contactListId
* @return
*/
private Map<String, Object> encapMap(String contactListId) {
Map<String, Object> dataMap = new HashMap<String, Object>();
FasSuperviseQualityWeeklyExt Ext = new FasSuperviseQualityWeeklyExt();
FasSuperviseQualityWeeklyServiceDto dto = new FasSuperviseQualityWeeklyServiceDto(Ext, request, FasConstant.MODE_INSERT);
dto.getMainInfo().setSuperviseQualityWeeklyId(contactListId);
FasSuperviseQualityWeeklyExt data = FasSupervise.queryQualityWeeklybyID(dto);
//基础施工进度(周报)表查询(总进度)
FasSuperviseCprogressWeeklyExt cprext = new FasSuperviseCprogressWeeklyExt();
FasSuperviseCprogressWeeklyServiceDto cprdto = new FasSuperviseCprogressWeeklyServiceDto(cprext, buildPagenation());
cprdto.getMainInfo().setSuperviseQualityWeeklyId(contactListId);
short s = 0;
cprdto.getMainInfo().setTypesConstructProgress(s);
FasSuperviseCprogressWeeklyEntity cprdata = Cprogress.CprogressSeletOne(cprdto);
//基础施工进度(周报)表查询(本周进度)
FasSuperviseCprogressWeeklyExt thisext = new FasSuperviseCprogressWeeklyExt();
FasSuperviseCprogressWeeklyServiceDto thisweekdto = new FasSuperviseCprogressWeeklyServiceDto(thisext, buildPagenation());
thisweekdto.getMainInfo().setSuperviseQualityWeeklyId(contactListId);
short s1 = 1;
thisweekdto.getMainInfo().setTypesConstructProgress(s1);
FasSuperviseCprogressWeeklyEntity thisweekdata = Cprogress.CprogressSeletOne(thisweekdto);
//本周天气(周报)表查询(天气)
FasSuperviseTwWeatherWeeklyExt twtext = new FasSuperviseTwWeatherWeeklyExt();
FasSuperviseTwWeatherWeeklyServiceDto twtdto = new FasSuperviseTwWeatherWeeklyServiceDto(twtext, buildPagenation());
twtdto.getMainInfo().setSuperviseQualityWeeklyId(contactListId);
twtdto.getMainInfo().setAtmosphericTemperature(s);
FasSuperviseTwWeatherWeeklyEntity twtdata = TwWeatherWeekly.twWeatherWeeklySelectOne(twtdto);
//本周天气(周报)表查询(气温)
FasSuperviseTwWeatherWeeklyExt twext = new FasSuperviseTwWeatherWeeklyExt();
FasSuperviseTwWeatherWeeklyServiceDto twdto = new FasSuperviseTwWeatherWeeklyServiceDto(twtext, buildPagenation());
twtdto.getMainInfo().setSuperviseQualityWeeklyId(contactListId);
twtdto.getMainInfo().setAtmosphericTemperature(s1);
FasSuperviseTwWeatherWeeklyEntity twdata = TwWeatherWeekly.twWeatherWeeklySelectOne(twdto);
//项目名称
dataMap.put("pjName", data.getPjName());
//离场时间
String leaveTimeString = formatter.format(data.getProjectLeaveTime());
dataMap.put("projectLeaveTime", leaveTimeString);
List<FileInfo> fileInfos = QweeklyFiles.queryImagesByquality(contactListId);
List<FasSuperviseTwIinfoWeeklyEntity> slist = new ArrayList<>();
for (FileInfo file : fileInfos) {
try {
InputStream fileStream;
FasSuperviseTwIinfoWeeklyEntity fas = new FasSuperviseTwIinfoWeeklyEntity();
//说明描述赋值
FasSuperviseTwIinfoWeeklyEntity ext = TwIinfoWeek.selectFile(file.getFileKey());
String superviseSescription = ext.getSuperviseSescription();
fas.setSuperviseSescription(ext.getSuperviseSescription());
//图片转换为16进制编码赋值根据服务器的存储位置返回InputStream类型数据
fileStream = fileService.getFileStream(file.getFilePath());
//创建InputStream对象放入图片返回InputStream类型16进制编码数据
//fileStream = new FileInputStream("D:\\微信图片_20191017140645.png");
byte[] bytes = new byte[fileStream.available()];
fileStream.read(bytes);
fileStream.close();
BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(bytes);
fas.setSuperviseTwIiwId(encode);
slist.add(fas);
} catch (Exception e) {
e.printStackTrace();
}
}
dataMap.put("dataList",slist);
return dataMap;
}
//调用图片返回InputStream数据
@Override
public InputStream getFileStream(String filePath) throws Exception{
String realPath = fasConstant.getValue(FasConstant.FILEPATH) + filePath;
File file = new File(realPath);
InputStream inputStream = new FileInputStream(file);
return inputStream;
}
Ftl调用
js的地址跳转