freemarker导出word档

时间:2023-03-09 13:30:03
freemarker导出word档

1.word另存为xml;2.xml文件后缀名改成ftl;3.编写完整json字符串备用;4.修改ftl中动态字段为json中对应字段名;5.编写java代码自动生成word文件;(注意:换行用<w:br/>)

消防设施故障维修记录表.doc:

freemarker导出word档

freemarker导出word档

package freemarkerExportWord;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map; import dto.EmergencyMaintenanceItem;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.sf.json.JSONObject; public class FreemarkerExportWordTest2 {
public static void main(String[] args){
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
} private static void test() throws Exception{
/** 初始化配置文件 **/
Configuration configuration = new Configuration();
/** 设置编码 **/
configuration.setDefaultEncoding("utf-8");
/** 我的ftl文件是放在G盘的**/
String fileDirectory = "G:\\freemarker导出word\\2";
/** 加载文件 **/
configuration.setDirectoryForTemplateLoading(new File(fileDirectory));
/** 加载模板 **/
Template template = configuration.getTemplate("消防设施故障维修记录表.ftl");
/** 准备数据 **/
Map<String,Object> dataMap = new HashMap<String,Object>();
String maintenanceData = "{\"emergencyMaintenanceItem\":{\"emergencyMaintenances\":[{\"maintenanceTime\":\"2018-06-27 16:31:53\",\"maintenanceMans\":\"张三\",\"faultLocation\":\"出口加工区大楼2层\",\"record\":\"\",\"safetyMeasure\":\"大多数阿苏飞洒地方阿斯蒂芬啊撒反对\",\"applyMan\":\"加工区\",\"faultDetail\":\"请尽快解决\",\"maintenanceMethod\":\"啊十分大师傅的发生阿斯顿\",\"applyTime\":\"2018-04-23 14:12:20\",\"stopSystem\":\"\",\"confirm\":\"东方不败\"},{\"maintenanceTime\":\"2018-06-26 16:33:39\",\"maintenanceMans\":\"李四\",\"faultLocation\":\"\",\"record\":\"\",\"safetyMeasure\":\"发顺丰打大师傅撒旦发阿斯顿发顺丰打啊\",\"applyMan\":\"\",\"faultDetail\":\"\",\"maintenanceMethod\":\"阿斯顿发生阿斯蒂芬阿三\",\"applyTime\":\"\",\"stopSystem\":\"\",\"confirm\":\"123\"}]}}";
fillDate(dataMap,maintenanceData);
/** 指定输出word文件的路径 **/
String outFilePath = "G:\\freemarker导出word\\2\\消防设施故障维修记录表.doc";
File docFile = new File(outFilePath);
FileOutputStream fos = new FileOutputStream(docFile);
Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
template.process(dataMap,out); if(out != null){
out.close();
}
} private static void fillDate(Map<String,Object> dataMap,String maintenanceData) {
@SuppressWarnings("static-access")
JSONObject obj = new JSONObject().fromObject(maintenanceData);//将json字符串转换为json对象
JSONObject emergencyMaintenanceObj = obj.getJSONObject("emergencyMaintenanceItem"); EmergencyMaintenanceItem emergencyMaintenanceItem = (EmergencyMaintenanceItem)JSONObject.toBean(emergencyMaintenanceObj,EmergencyMaintenanceItem.class);
dataMap.put("emergencyMaintenanceItem",emergencyMaintenanceItem); }
}