1.新建 word文件,调整好格式
如图:
另存为xml文件
修改扩展名字为ftl就可以了,
把模版数据填充到模版中:
public static String jsonToword(JSONObject jsonObject) {
String wordPath = null;
try {
JSONObject agreement = jsonObject.getJSONObject("agreement");
String tempFileName = "tpl_protocol_book";
JSONArray lossList = agreement.getJSONArray("lossList");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < lossList.size(); i++) {
if (i == lossList.size() - 1) {
sb.append(lossList.getJSONObject(i).getStr("personName"));
} else {
sb.append(lossList.getJSONObject(i).getStr("personName") + "、");
}
}
//这里的文件名用uuid,因为暂存的时候可能没有录入客户姓名
String fileName = UuidUtils.getUUID() + ".docx";
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("damageDate", agreement.getStr("damageDate"));
dataMap.put("licenseNo", agreement.getStr("licenseNo"));
dataMap.put("damageAddress", agreement.getStr("damageAddress"));
dataMap.put("earlyPayAmount", agreement.getStr("earlyPayAmount"));
dataMap.put("sumIndemnity", agreement.getStr("sumIndemnity"));
dataMap.put("insuredDuty", agreement.getStr("insuredDuty"));
dataMap.put("payInfoList", agreement.getJSONArray("payInfoList"));
dataMap.put("lossList", lossList);
dataMap.put("remark", agreement.getStr("remark"));
dataMap.put("insuredName", agreement.getStr("insuredName"));
dataMap.put("insuredCertiCode", agreement.getStr("insuredCertiCode"));
dataMap.put("beInsureSignList", jsonObject.containsKey("beInsureSignList") ? jsonObject.getJSONArray("beInsureSignList") : new JSONArray());
dataMap.put("hurtSignList", jsonObject.containsKey("hurtSignList") ? jsonObject.getJSONArray("hurtSignList") : new JSONArray());
String dir = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "tpl_document" + File.separator + "temp" + File.separator;
FreeMarkerUtil.outDocumentFile(dir.substring(1) + fileName, fileName, tempFileName, dataMap);
wordPath = dir.substring(1) + fileName;
} catch (Exception e) {
e.printStackTrace();
}
return wordPath;
}
@Slf4j
@Component
public class FreeMarkerUtil {
private static Configuration config;
/**
* @param tempFilePath 临时文件路径
* @param finalFilePath 最终文件路径
* @param tempFileName 模版文件路径
* @param dataMap 模版数据
* @return
*/
public static boolean outDocumentFile(String tempFilePath, String finalFilePath, String tempFileName, Map<String, Object> dataMap) {
try {
/** 初始化模版配置文件 **/
config = new Configuration();
/** 设置编码 **/
config.setDefaultEncoding("utf-8");
String fileDirectory = null;
fileDirectory = ResourceUtils.getFile("classpath:tpl_document").getAbsolutePath();
/** 加载文件 **/
config.setDirectoryForTemplateLoading(new File(fileDirectory));
String docxTemplate = ResourceUtils.getFile("classpath:tpl_document" + File.separator + tempFileName + ".docx").getAbsolutePath();
/** 加载模板 **/
Template template = config.getTemplate(tempFileName + ".ftl");
/** 指定输出word文件的路径 **/
FileOutputStream fos = new FileOutputStream(new File(tempFilePath));
Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
template.process(dataMap, out);
if (out != null) {
out.close();
}
outDocx(new File(tempFilePath), docxTemplate, finalFilePath);
} catch (Exception e) {
log.error("outDocumentFile 生成文档失败!, 使用的模板名是: {}", tempFileName, e);
return false;
}
log.info("outDocumentFile 生成文档成功!, 使用的模板名是: {}", tempFileName);
return true;
}
/**
* 转为doc
*
* @param documentFile 动态生成数据的docunment.xml文件
* @param docxTemplate docx的模板
* @param toFilePath 需要导出的文件路径
*/
public static void outDocx(File documentFile, String docxTemplate, String toFilePath) throws ZipException, IOException {
try {
File docxFile = new File(docxTemplate);
ZipFile zipFile = new ZipFile(docxFile);
Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(toFilePath));
int len = -1;
byte[] buffer = new byte[1024];
while (zipEntrys.hasMoreElements()) {
ZipEntry next = zipEntrys.nextElement();
InputStream is = zipFile.getInputStream(next);
// 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
zipout.putNextEntry(new ZipEntry(next.toString()));
if ("word/document.xml".equals(next.toString())) {
InputStream in = new FileInputStream(documentFile);
while ((len = in.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
in.close();
} else {
while ((len = is.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
is.close();
}
}
zipout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}