读取跟着教程做很容易,下载自己摸索属实费了点功夫 按照官网教程来做https://alibaba-easyexcel.github.io 新建了一个springboot工程,然后访问地址,确实可以弹出下载页,但是现有项目整合了springsecurity,不管怎么搞,前端点击下载按钮总是没反应。 后台部分: 1:controller
@ApiOperation(value = "导出excel")
@GetMapping("/getExcel")
public void getExcel(HttpServletResponse response) throws IOException {
List<MemoryExcel> list= memoryAnalyseService.getExcelList();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String name = sdf.format(date);
String fileName = URLEncoder.encode(name+"内存数据", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), MemoryExcel.class).sheet("模板").doWrite(list);
}
MemoryExcel 是需要生成的excel模型,每一列的属性,如下图,getExcelList 是通过查询数据库表,需要生成的MemoryExcel的List集合,
这里后台就处理完了,主要是前端需要处理了,
首先导入:import {exportExcels} from "@/api/computer/exportExcel"; exportExcel.js里面定义了请求后台方法:
import exportExcel from '@/utils/utils'
export function exportExcels(data) {
return exportExcel({
url: '/memory/getExcel',
method: 'get',
responseType: 'blob'
})
}
再定义utils.js
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
const service = axios.create({
baseURL: process.env.BASE_API,
timeout: 500000
})
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['Authorization'] = getToken()
}
return config
},
error => {
console.log(error)
Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
let disposition = response.headers['content-disposition'];
let filename = disposition?disposition.substring(disposition.indexOf('=')+1,disposition.indexOf('.')):"下载文件";
let newName = decodeURI(filename)
let extName =disposition.substring(disposition.indexOf('.')+1)
let blob = new Blob([response.data],{type: 'application/vnd.ms-excel'});
let link = document.createElement("a");
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", false, false);
link.href = URL.createObjectURL(blob);
link.download = newName+"."+extName;
link.style.display = "none";
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href);
},
error => {
console.log('err' + error)
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
因为这是用vue模板做的,所以这上面的getToken 等就没写了,如果这里没处理好,访问接口会报错401,未登录token过期什么的,
下载页面的的按钮绑定下载方法exportExcel 在methods里面定义方法:
exportExcel(){
exportExcels().then()
}
前台部分完成,保存、测试: 参考链接:Vue+easyexcel实现excel导入导出
|