EasyWord导出
1、Maven依赖包
<dependency>
<groupId>com.sushengren</groupId>
<artifactId>easyword</artifactId>
<version>1.1.3</version>
</dependency>
2、实体类字段绑定
此处是在实体类的字段上写上注解,注解里面的value就是在模板文件里的绑定关系
{name}绑定模板
@WordProperty("名字")
private String name;
@WordProperty("地址")
private String address;
@WordProperty("phone")
private String phone;
@WordProperty("信息")
@ApiModelProperty("信息")
@TableField(exist = false)
List<AttDeviceDemobilizeRecordEntity> recordEntities;
上面list的内容
@WordProperty("序号")
@TableField(exist = false)
@ApiModelProperty(value = "导出排序",hidden = true)
private Integer idSeq;
@ApiModelProperty("关联id")
@TableField(value = "demobilize_id")
private int demobilizeId;
3、 代码实现
package com.test.controller;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.alibaba.fastjson.JSON;
import com.sushengren.easyword.EasyWord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@Api(tags = "导出")
@RequestMapping("/word")
public class WordController {
@Autowired
TestService testService;
@ApiOperation("导出")
@PostMapping("/download")
public void download(HttpServletResponse response, Integer id) throws IOException {
if (id == null) {
return;
}
try {
Entity data = Service.getDemobById(id);
//设置浏览器导出word格式文件
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setCharacterEncoding("utf-8");
//这里注意要拼接docx后缀,导出什么就拼接什么后缀,不然上测试会报请求错误,格式无法处理错误
//Invalid content disposition format
String fileName = "测试.docx";
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
Entity data = testService.getById(id);
//以流的形式 获取resources下目中录模板文件
InputStream file = new ClassPathResource("templates/动复原导出.docx").getInputStream();
// XWPFDocument word = WordExportUtil.exportWord07(templateFile.getPath(),params);
EasyWord.of(file).doWrite(data).toOutputStream(response.getOutputStream());
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<>(16);
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
}
4、word模板,导出的多条需要选中多的那个表格,并且添加书签,不然只能导出一条记录。(选择书签时不可以把最上面的书签选中,不然一起循环)