- 先写一个word模板,将变量用${} 样式填充在将要显示的值处
- List类型的数据,需要指定序号进行循环
- word模板另存为xml文件 注意:有时候会在${}之间多出来样式,需删掉
- controller的方法中new一个map,将要填充在word中的变量都放到map里,记得指定输出流的编码(utf-8),否则可能报内容有错误,不能读取word文档。
// 如果数据库中的数据为null,转换为0
public String toString (Object obj){
return (obj == null) ? "0" : obj.toString();
}
@RequestMapping(value = "/download")
public void export(HttpServletResponse response, Integer id) {
if (null != id) {
PaTrainWeekly paTrainWeekly = this.paTrainWeeklyService.findById(id);
List<PaTrainNewReceiveItems> receiveItems = this.paTrainNewReceiveItemsService.findByWeeklyId(id);
Map<String, String> data = new HashMap<>();
data.put("year", toString(paTrainWeekly.getYear()));
data.put("month", toString(paTrainWeekly.getMonth()));
if (ObjectUtil.isNotBlank(receiveItems)) {
// 循环集合里的数据
for(int i = 0; i < receiveItems.size(); i++){
PaTrainNewReceiveItems tr = receiveItems.get(i);
if(tr != null){
String trainNum = toString(tr.getTrainNum());
String company = tr.getCompany();
String receiveNum = new SimpleDateFormat("yyyy-MM-dd").format(tr.getReceiveNum());
// 第一列增加一个序号
data.put("num_"+(i+1), toString(i+1));
data.put("receiveItems_"+ (i+1) +"_trainNum", trainNum);
data.put("receiveItems_"+ (i+1) +"_company", company);
}
}
// word里暂定十条数据,因为不确定集合里有多少条数据,少于10条的用null代替。
if(10>receiveItems.size()){
for(int i = receiveItems.size(); 10> i; i++){
data.put("num_"+(i+1), "");
data.put("receiveItems_"+ (i+1) +"_trainNum", "");
data.put("receiveItems_"+ (i+1) +"_company","");
}
}
}
String wordData = FileUtils.wordData(data, "trainWeekly.xml");
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
String fileName = DateUtils.formatDate(new Date())+".doc";
response.setHeader("Content-Disposition", "attachment;filename=".concat(fileName));
try {
OutputStream out = response.getOutputStream();
out.write(wordData.getBytes("UTF-8"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String wordData(Map<String, String> data, String template) {
String tmp = readTemplate(template);
logger.debug("template {}", tmp);
Set<Entry<String, String>> set = data.entrySet();
for (Entry<String, String> entry : set) {
String k = entry.getKey();
String v = entry.getValue();
if (v == null) {
v = "";
}
k = "${" + k + "}";
tmp = tmp.replace(k, v);
}
return tmp;
}
public static String readTemplate(String name) {
StringBuffer buffer = new StringBuffer();
try {
URL url = FileUtils.class.getResource("/files/" + name);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(url.getPath()), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buffer.toString();
}
/**
* 将Date格式化成符合默认日期格式的字符串
*
* @param date
* @return 返回样例:2012-03-29
*/
public static String formatDate(Date date) {
SimpleDateFormat formatTool = new SimpleDateFormat();
formatTool.applyPattern(DAY_PATTERN);
return formatTool.format(date);
}