引入依赖:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
一:导出方法
/*********导出部分*********/
public static void exportExcel(String realPath, Map<String, Object> map, String fileName, HttpServletResponse response) throws IOException {
//sheet封装
Map<String, Object> sheetMap = new HashMap<String, Object>();
sheetMap.put("list", map.get("list"));
sheetMap.put("projects", map.get("projects"));
TemplateExportParams params = new TemplateExportParams(realPath,true);
// 设置sheetName,若不设置该参数,则使用得原本得sheet名称
// String[] sheetNameArray = {"执法分析","整体趋势"} ;
// params.setSheetName(sheetNameArray);
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName+".xlsx", "UTF-8"));
ServletOutputStream outStream = null;
try {
outStream = response.getOutputStream();
workbook.write(outStream);
} finally {
outStream.close();
}
} catch (IOException e) {
throw new BadRequestException( e.getMessage());
}
}
二:接口
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) {
try {
// TemplateExportParams templatePath = new TemplateExportParams("D:/WorkSpace/模板.xls");
Map<String, Object> map = new HashMap<>();
map.put("index", "序号");
map.put("year", "年度");
List<one> list = dataOneService.list();
List<Project> projects = ProjectService.list();
map.put("list", list);
map.put("projects", projects);
//sheet封装
ExcelUtils.exportExcel("D:/WorkSpace/模板.xls", map, "新导出文件.xlsx", response);
} catch (Exception ex) {
throw new BadRequestException(ex.getMessage());
}
}
时间格式:
?
?
前端:
js:
/**
* 导出excel
* @returns data
*/
export function expExcel() {
return request({
url: '/api/one/exportExcel',
method: 'get',
responseType: 'blob'
})
}
method:
expExcel(){
expExcel().then((res) =>{
const downUrl = window.URL.createObjectURL(new Blob([res]));
const a = window.document.createElement('a');
a.href = downUrl;
a.download = `文件.xlsx`;
a.click();
window.URL.revokeObjectURL(downUrl);
})
}
|