-
准备好模板,并调整好模板中的格式
-
将word文档另存为Word 2003 XML格式
-
更改模板后缀xml为ftl
-
使用freemarker标签替换数据
-
获取模板代码
private static Configuration configuration = null; private static Map<String, Template> allTemplates = null; static { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(WordGenerator.class, "/download"); allTemplates = new HashMap<String, Template>(); try { // 模板 Template recordTemplates = configuration.getTemplate( "test.ftl", "UTF-8"); allTemplates.put("template", recordTemplates); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }
-
生成word代码
public static File createDoc(Map<?, ?> dataMap, String type, String tempFileDir) { // 临时文件名称 String name = "temp" + (int) (Math.random() * 100000) + ".doc"; File fileMkDir = new File(tempFileDir); // 如果文件夹不存在则创建 if (!fileMkDir.exists() && !fileMkDir.isDirectory()) { fileMkDir.mkdir(); } File file = new File(tempFileDir, name); // 获取模板 Template template = allTemplates.get(type); try { Writer out = null; FileOutputStream fos = null; fos = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); out = new BufferedWriter(writer); template.process(dataMap, out); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return file; }
注: 1.若导出内容包含图片,需将图片转为base64编码
public static String getBase64ImgStrLocal(String imgFile) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
if (imgFile == null || imgFile == "") {
return "";
}
File tempFile = new File(imgFile);
if (!tempFile.exists() || !tempFile.isFile()) {
return "";
}
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(tempFile.getAbsolutePath());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
// String returnData = new String(Base64.encodeBase64(data));
String returnData = encoder.encode(data);
return returnData == null ? "" : returnData;
}
2.导出的word中包含特殊字符需进行替换:
导出字段为null需替换成"",使用freemarker标签:${content!''}或${((content)!'')?html}(可替换特殊字符)
7.设置以浏览器的方式进行下载:
@RequestMapping("/export")
@ResponseBody
public void export(HttpServletRequest request,HttpServletResponse response) {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
request.setCharacterEncoding("utf-8");
//获取数据****
Map<String,Object> map = ************** /
/获取数据*****
file = WordGenerator.createDoc(map, "template", tmpStore);
fin = new FileInputStream(file);
String filename = "导出的word文件名";
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件
filename = new String(filename.getBytes("gb2312"), "ISO8859-1");
response.addHeader("Content-Disposition", "attachment;filename=" + """ +
filename + ".doc");
out = response.getOutputStream();
byte[] buffer = new byte[512];
// 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {
fin.close();
} if (out != null) {
out.close();
} if (file != null) {
file.delete(); // 删除临时文件
}
}