前言:
导出word的需求其实在日常工作中用到的地方还不少,于是想写一篇文章好好记录一下,在导出之前,需要了解一下关于浏览器如何处理servlet的后台数据。具体可以了解一下http通信下载行为在servlet的实现。
==导出的工具类代码来源于网络,如有侵权可以联系我删除文章==
个人使用==ftl==作为word导出模板引擎,有很多模板引擎可以选,个人经过查阅资料发现ftl用的比较多,所以选择这一种
码云地址:
文章牵扯代码比较多,如果要看具操作可以查看我自己瞎弄的一个码云地址:
https://gitee.com/lazyTimes/interview.git
效果演示:
给了一个测试页面,临时写了一些脚本,可以作为参考(后续会贴Html代码进去)

点击提交,导出内容, 导出word报告

导出之后,打开word内容为:

实现步骤 - 制作word模板
第一步 新建word,制作成果样板
将需要导出word的内容,先粘贴到一个新建的word文件里面

第二步 转存格式 -> xml
选择文件“另存为”,将格式设置为xml格式

第三步 格式化文件
将文件放到idea或者支持格式化的软件里面,进行格式化,保存:
注意占位符要匹配

第四步:模板数据替换占位符
在word页面将需要导入数据的地方,替换占位符
需要注意内容处理的时候: ${ filename} 有可能被切割为多个部分,我们需要把多个切割部分,改为下面的样式

一定记得所有的改动之后,马上打开xml格式的word,确认是不是改崩了
上面的步骤完成,说明有一个word模板做好了
第五步:制作ftl文件,word模板成型
在项目里面新建一个ftl文件,同时需要在工具类中配置,同时把做好站位符操作的xml内容贴进去
代码实现 - 导出代码
- 工具类的配置如下:
WordGeneratorUtil.java:
1 2 3 4 5 6 7 8 9
|
public static final class FreemarkerTemplate { public static final String REPORT = "report"; public static final String REC_RECOMMEND = "recRecommend";
}
|
在静态的代码块里面,需要注入对应的模板配置
1 2 3
| allTemplates.put(FreemarkerTemplate.REPORT, configuration.getTemplate(FreemarkerTemplate.REPORT + ".ftl")); allTemplates.put(FreemarkerTemplate.REC_RECOMMEND,configuration.getTemplate(FreemarkerTemplate.REC_RECOMMEND + ".ftl"));
|
- 在配置完成之后,导出的时候就可以找到对应的文件了
- 建立一个通用的导出方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public static File createDoc(String freemarkerTemplateName, String wordName, Map<String, String> dataMap) { try { File f = new File(wordName); Template t = allTemplates.get(freemarkerTemplateName); Writer w = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8); t.process(dataMap, w); w.close(); return f; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("生成word文档失败"); } }
|
工具类完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| package com.zxd.interview.export;
import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.util.CollectionUtils;
import java.io.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map;
public final class WordGeneratorUtil { private static Configuration configuration = null; private static Map<String, Template> allTemplates = null; private static final String TEMPLATE_URL = "/templates";
public static final class FreemarkerTemplate { public static final String Test = "test"; public static final String REPORT = "report"; public static final String REC_RECOMMEND = "recRecommend";
}
static { configuration = new Configuration(Configuration.VERSION_2_3_28); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(WordGeneratorUtil.class, TEMPLATE_URL); allTemplates = new HashMap(4); try { allTemplates.put(FreemarkerTemplate.Test, configuration.getTemplate(FreemarkerTemplate.Test + ".ftl")); allTemplates.put(FreemarkerTemplate.REPORT, configuration.getTemplate(FreemarkerTemplate.REPORT + ".ftl")); allTemplates.put(FreemarkerTemplate.REC_RECOMMEND, configuration.getTemplate(FreemarkerTemplate.REC_RECOMMEND + ".ftl")); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }
private WordGeneratorUtil() { throw new AssertionError(); }
public static File createDoc(String freemarkerTemplateName, String wordName, Map<String, String> dataMap) { try { File f = new File(wordName); Template t = allTemplates.get(freemarkerTemplateName); Writer w = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8); t.process(dataMap, w); w.close(); return f; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("生成word文档失败"); } }
}
|
调用层:
- 在业务层,将需要导出的数据,根据占位符的i信息进行赋值,注意不能漏,否则导出之后的文件会打不开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Override public File exportQualityStep4Word(WordReportDTO exportWordRequest) { Map<String, String> datas = new HashMap(QualityConstants.HASH_MAP_INIT_VALUE); datas.put("schoolName", exportWordRequest.getSchoolName()); datas.put("title1", exportWordRequest.getBaseSituation()); datas.put("title2", exportWordRequest.getLearningEnvRec()); datas.put("title3", exportWordRequest.getLearningEnvPro()); datas.put("title4", exportWordRequest.getDayLifeRec()); datas.put("title5", exportWordRequest.getDayLifePro()); datas.put("title6", exportWordRequest.getLearningActivityRec()); datas.put("title7", exportWordRequest.getLearningActivityPro()); datas.put("title8", exportWordRequest.getDevRecommend());
datas.put("base64_1", exportWordRequest.getBase64_1()); datas.put("base64_2", exportWordRequest.getBase64_2()); datas.put("base64_3", exportWordRequest.getBase64_3()); datas.put("base64_4", exportWordRequest.getBase64_4()); datas.put("base64_5", exportWordRequest.getBase64_5()); datas.put("base64_6", exportWordRequest.getBase64_6());
return WordGeneratorUtil.createDoc(WordGeneratorUtil.FreemarkerTemplate.REPORT, exportWordRequest.getWordName(), datas); }
|
- 下面是生成报表导出的基本操作,可以在用到的地方复制过去改动即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
@PostMapping("/quality/exportword") @ResponseBody public void povertyExportWord(HttpServletRequest request, HttpServletResponse response, WordReportDTO exportWordRequest) {
File file = qualityReportService.exportQualityStep4Word(exportWordRequest);
InputStream fin = null; OutputStream out = null; try { fin = new FileInputStream(file);
response.setCharacterEncoding(QualityConstants.UTF_8); response.setContentType(QualityConstants.CONTENT_TYPE_WORD); String filename = exportWordRequest.getWordName(); String agent = request.getHeader(QualityConstants.USER_AGENT); String filenameEncoder = ""; if (agent.contains(QualityConstants.MSIE)) { filenameEncoder = URLEncoder.encode(filename, QualityConstants.UTF_8); filenameEncoder = filenameEncoder.replace("+", " "); } else if (agent.contains(QualityConstants.FIREFOX)) { BASE64Encoder base64Encoder = new BASE64Encoder(); filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes(QualityConstants.UTF_8)) + "?="; } else { filenameEncoder = URLEncoder.encode(filename, QualityConstants.UTF_8); } response.setHeader(QualityConstants.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.setHeader(QualityConstants.CONTENT_TYPE, QualityConstants.CONTENT_TYPE_STEAM); response.setHeader(QualityConstants.CONTENT_DISPOSITION, "attachment;filename=" + filenameEncoder + ".doc"); response.setHeader(QualityConstants.CONNECTION, QualityConstants.CLOSE); response.setContentType(QualityConstants.CONTENT_TYPE_DOWNLOAD); out = response.getOutputStream(); byte[] buffer = new byte[QualityConstants.BYTE_512]; int bytesToRead = QualityConstants.NUM_MINUS_1; while ((bytesToRead = fin.read(buffer)) != QualityConstants.NUM_MINUS_1) { out.write(buffer, QualityConstants.NUM_ZERO, bytesToRead); }
} catch (Exception e) { throw new RuntimeException(QualityConstants.FARIURE_EXPORT, e); } finally { try { if (fin != null) { fin.close(); } if (out != null) { out.close(); } if (file != null) { file.delete(); } } catch (IOException e) { throw new RuntimeException(QualityConstants.FARIURE_EXPORT, e); } }
}
|
导出实体dto
下面写了一个导出的实体dto,实体对象可以自己定制:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| package com.zxd.interview.dto;
public class TestReportDTO {
private String test0;
private String test1;
private String test2;
private String test4;
private String test5;
private String test6;
private String wordName;
public String getTest0() { return test0; }
public void setTest0(String test0) { this.test0 = test0; }
public String getTest1() { return test1; }
public void setTest1(String test1) { this.test1 = test1; }
public String getTest2() { return test2; }
public void setTest2(String test2) { this.test2 = test2; }
public String getTest4() { return test4; }
public void setTest4(String test4) { this.test4 = test4; }
public String getTest5() { return test5; }
public void setTest5(String test5) { this.test5 = test5; }
public String getTest6() { return test6; }
public void setTest6(String test6) { this.test6 = test6; }
public String getWordName() { return wordName; }
public void setWordName(String wordName) { this.wordName = wordName; }
@Override public String toString() { return "TestReportDTO{" + "test0='" + test0 + '\'' + ", test1='" + test1 + '\'' + ", test2='" + test2 + '\'' + ", test4='" + test4 + '\'' + ", test5='" + test5 + '\'' + ", test6='" + test6 + '\'' + '}'; } }
|
常量配置模块:
个人很不喜欢硬编码这东西,又丑又难看,所以很多东西会用不可变对象替代.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
| package com.zxd.interview.constant;
public class QualityConstants {
public static final int EVENTID = 12;
public static final int NUM_ZERO = 0;
public static final int NUM_ONE = 1;
public static final int NUM_TWO = 2;
public static final int NUM_MINUS_1 = -1;
public static final int BYTE_512 = 512;
public static final int CODE_500 = 500;
public static final String CODE_500_MSG_1 = "状态非法!";
public static final String CODE_500_MSG_2 = "非督导用户不允许查看质量检测记录!";
public static final String CODE_500_MSG_3 = "这条质量监测已经完成!无法修改!";
public static final String CODE_500_MSG_4 = "提交失败,材料上传不能为空";
public static final String CODE_500_MSG_5 = "提交失败,请稍后重试或联系管理员!";
public static final String CODE_500_MSG_6 = "提交失败,意见反馈不能为空!";
public static final int CODE_405 = 405;
public static final String CODE_405_MSG_1 = "该信息只允许督导查看!";
public static final int CODE_200 = 200;
public static final String CODE_200_MSG_1 = "提交成功!";
public static final String DELETE_FAIRURE_MSG = "删除失败,尚未选择记录!";
public static final String NO_RECORD_SELECTED = "尚未选择记录!";
public static final String UTF_8 = "utf-8";
public static final int PID = 0;
public static final int DEFUALT_LAYER = 1;
public static final Integer MIN_SCORE = 1;
public static final Integer MAX_SCORE = 7;
public static final int HASH_MAP_INIT_VALUE = 32;
public final static String WHOLE_AVERAGE = "全园平均分";
public final static String QUERY_FAIRURE = "查询失败";
public final static String SUCCESS_MSG = "操作成功!";
public final static String FARIURE_MSG = "操作失败!";
public final static String FARIURE_EXPORT = "导出失败!";
public final static String CONTENT_TYPE_WORD = "application/msword";
public final static String CONTENT_TYPE_DOWNLOAD = "application/x-download";
public final static String CONTENT_TYPE_STEAM = "application/octet-stream;charset=UTF-8";
public final static String USER_AGENT = "User-Agent";
public final static String CONTENT_TYPE = "Content-Type";
public final static String CONNECTION = "Connection";
public final static String CLOSE = "close";
public final static String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public final static String CONTENT_DISPOSITION = "Content-Disposition";
public final static String MSIE = "MSIE";
public final static String FIREFOX = "Firefox";
public final static String MODULE_STEP3_REPORT = "qualityreport";
public final static String MODULE_STEP1_MATERIAL = "qualitymetrail";
public final static int NUM_3 = 3;
public final static int NUM_4 = 4;
public final static int NUM_5 = 5;
public final static int NUM_6 = 6;
public final static int NUM_7 = 7;
public final static int NUM_8 = 8;
public final static int NUM_9 = 9;
public final static int NUM_10 = 10;
public final static int NUM_11 = 11;
public final static int NUM_12 = 12;
public final static int NUM_13 = 13;
public final static int NUM_14 = 14;
public final static int NUM_15 = 15;
public final static int NUM_16 = 16;
public final static int NUM_17 = 17;
public final static int NUM_18 = 18;
public final static int NUM_19 = 19;
public final static int NUM_20 = 20;
public final static String DECIMAL_Format = "######.00";
}
|
页面层处理:
前端增加一个form提交,使用form提交表单数据,实现word导出功能:
(注意使用的模板引擎是thymeleaf)
html代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| <!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<head> <meta charset="UTF-8"> <title>Title</title>
</head> <body> <div class="container"> <div id="vue1" class="row">
<form method="post" action="/quality/exportword"> <div> 导出word名称:<input class="form-control" type="text" name="wordName"> </div>
<div> test0:<input type="text" class="form-control" name="test0"> test1:<input type="text" class="form-control" name="test1"> test2:<input type="text" class="form-control" name="test2"> test4:<input type="text" class="form-control" name="test4"> test5:<input type="text" class="form-control" name="test5"> test6:<input type="text" class="form-control" name="test6"> </div>
<input type="submit" class="btn btn-danger" value="提交"> </form>
</div> </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script> <script th:src="@{/js/exportword.js}"></script> </html>
|
js代码
使用js代码处理form表单提交,使用了jquery进行导出,其实一直不太懂前端怎么导出后台产生的二进制流,做法挺多,下次写一篇文章好好汇总一下几种用法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| var v1 = new Vue({ el: '#vue1', data: { counter: 0, student: { test0:'', test1:'', test2:'', test3:'', test4:'', test5:'', test6:'', wordName: '',
} }, methods: { test: function () { console.log(this.counter); }, submit() { console.log(this.student); var url = '/quality/exportword'; var formData = JSON.stringify(this.student); this.$http.post(url, formData).then(function (data) { console.log(data); let blob = new Blob([data.data],{ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'}); let objectUrl = URL.createObjectURL(blob); window.location.href = objectUrl; }).catch(function () { console.log('test'); }); } } })
|
结尾:
个人水平一般,希望通过这篇文章可以帮到读者,有错误的地方欢迎指点,看到会及时改成,谢谢!
前段时间忙于面试找到新的地方工作了,等工作安定之后,会继续深耕博客和技术栈。