因为项目需求需要,临时写的有什么错误的地方望各位见谅,可以借鉴参考。
easypoi依赖包
<!-- 若依自带poi4.1.2依赖包,因此需要过滤掉引起冲突的依赖 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.3.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.3.0</version>
</dependency>
vue前端代码:
代码部分:
handleExport(name){
this.queryParams.projectId = this.projectId;
this.exportLoading = true;
return getProjectLogListArr(this.queryParams).then(res=>{
const url = window.URL.createObjectURL(new Blob([res],{type:"application/vnd.ms-excel;charset=utf-8"}));
const link = document.createElement('a');
link.href = url;
let fileName = name+".docx";
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
this.exportLoading = false;
});
}
js部分:
export function getProjectLogListArr(query) {
return request({
url: '/business/project/list/getProjectLogList',
method: 'get',
params: query,
// responseType: 'blob',
responseType: 'arraybuffer',
headers: { 'Authorization': 'Bearer ' + getToken() }
})
}
后端代码部分
Controller层代码:
@Value("${youfan.profile}")
private String profile;
@GetMapping("/list/getProjectLogList")
@ResponseBody
public void getProjectLogListArr(ProjectLog projectLog, HttpServletResponse response, HttpServletRequest request) throws IOException {
//查询所需导出的数据
List<ProjectLogVo> list = projectService.getProjectLogList(projectLog);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 标题数据添加
Map<String,Object> map = new HashMap<>();
// 模块路径
String templatePath = "static/template/projectLog.docx";
map.put("title",list.get(0).getProjectName());
// 渲染表格数据
List<Map<String,Object>> jobMap = new ArrayList<>();
Map<String,Object> job;
for(ProjectLogVo plv:list){
job = new HashMap<>();
job.put("userNick", StringUtils.isNotBlank(plv.getUserNick()) ? plv.getUserNick() : "系统");
job.put("name",plv.getName());
job.put("createTime", sdf.format(plv.getCreateTime()));
job.put("remark",plv.getRemark());
jobMap.add(job);
}
// 将数据存入map中
map.put("jobMap",jobMap);
//临时文件存放路径
// String temDir = profile;
//生成文件名
Long time = new Date().getTime();
//生成格式
String formatSuffix = ".docx";
//拼接后的文件名称
String fileName = time + formatSuffix;
// word文档导出工具方法
DeriveWord.exportWord(templatePath,profile,fileName,map,request,response);
}
Word工具类:
/**
* easyPoi 导出
* @param templatePath
* @param temDir
* @param fileName
* @param params
* @param request
* @param response
*/
public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(templatePath,"模板路径不能为空");
Assert.notNull(temDir,"临时文件路径不能为空");
Assert.notNull(fileName,"导出文件名不能为空");
Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");
String file = temDir+fileName;
if (!temDir.endsWith("/")){
temDir = temDir + File.separator;
}
File dir = new File(temDir);
// 文件是否存在,不存在创建文件
if (!dir.exists()) {
dir.mkdirs();
}
try {
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
}
// 根据模板导出数据
XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
// 根据地址创建临时文件
String tmpPath = temDir + fileName;
FileOutputStream fos = new FileOutputStream(tmpPath);
// 临时文件
doc.write(fos);
//关流
fos.close();
doc.close();
//下载文件
downloadFile(response,temDir+fileName);
} catch (Exception e) {
e.printStackTrace();
} finally {
//删除临时文件
delFileWord(temDir,fileName);
}
}
/**
* word文件下载
* @param response
* @param filePath
* @return
*/
public static String downloadFile(HttpServletResponse response, String filePath) {
String filename = "项目日志.docx";
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
os.close();
} catch (FileNotFoundException e1) {
//e1.getMessage()+"系统找不到指定的文件";
return "系统找不到指定的文件";
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "success";
}
/**
* 删除零时生成的文件
*/
public static void delFileWord(String filePath, String fileName) {
File file = new File(filePath + fileName);
File file1 = new File(filePath);
file.delete();
file1.delete();
}