阿里官方使用说明
https://www.yuque.com/easyexcel/doc/write#76fa967c
1、业务逻辑
/*** excel导出** @param response* @param basePingyuWords 实体类* @throws IOException*/@Overridepublic void downxlsx(HttpServletResponse response, BasePingyuWords basePingyuWords) throws IOException {//查询条件LambdaQueryWrapper<BasePingyuWords> lqw = getLqw(basePingyuWords);//获取数据List<BasePingyuWords> list = list(lqw);if (CollectionUtils.isNotEmpty(list)) {log.info("导出的数据:{}", list);//调用封装方法下载xlsx文件TjFileUtils.downxlsxByEasyexcel(response, BasePingyuWords.class, list);}}/*** 获取查询条件** @param basePingyuWords* @return*/private LambdaQueryWrapper<BasePingyuWords> getLqw(BasePingyuWords basePingyuWords) {//构造条件构造器LambdaQueryWrapper<BasePingyuWords> lqw = new LambdaQueryWrapper();//添加过滤条件lqw.like(StringUtils.isNotEmpty(basePingyuWords.getShopbelong()), BasePingyuWords::getShopbelong, basePingyuWords.getShopbelong()).like(StringUtils.isNotEmpty(basePingyuWords.getShortname()), BasePingyuWords::getShortname, basePingyuWords.getShortname());return lqw;}
2、easyexcel封装工具类
/*** 通过EasyExcel导出表格文件(下载失败了会返回一个有部分数据的Excel)* 1. 创建excel对应的实体对象* 2. 设置返回的 参数* 3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大** @param response 响应输出* @param head Java实体类的.class* @param data 导出data数据* @throws IOException*/public static void downxlsxByEasyexcel(HttpServletResponse response, Class head, Collection<?> data) throwsIOException {//设置返回文件类型response.setContentType("application/vnd.ms-excel");//设置编码格式utf-8response.setCharacterEncoding("utf-8");response.setHeader("Pragma", "No-cache");//这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("导出xlsx-" + TjDateUtils.getTodayString(), "UTF-8");response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");EasyExcel.write(response.getOutputStream(), head).registerWriteHandler(TjEasyExcelCellStyleUtils.getHorizontalCellStyleStrategy()) //设置表格样式.sheet("sheet1").doWrite(data);}
3、指定导出哪些数据,指定导出列名称
/*** 用户表字段*/@Data@TableName("users")@ExcelIgnoreUnannotated //只有@ExcelProperty注解的才会导出public class Users implements Serializable {private Long id;@ExcelProperty(value = "帐号") //导出列显示名@ColumnWidth(10) //列的宽度private String user_accout;@ExcelProperty(value = "姓名")@ColumnWidth(20)private String user_name;}
4、做controller接口给前端
/*** 下载excel文件** @param response HttpServletResponse* @param basePingyuWords 实体类*/@GetMapping("/downxlsx")void downxlsx(HttpServletResponse response, BasePingyuWords basePingyuWords) {try {basePingyuWordsService.downxlsx(response, basePingyuWords);} catch (IOException e) {e.printStackTrace();}}
5、前端去POST后端接口,下载文件
// 导出excel信息//import { downFile } from '@/utils/fileAction.js'tjdown() {this.$confirm('确定要导出当前查询的记录吗?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}).then(async () => {let res = await this.$api.base.pingyuWordsDown(this.queryInfo)console.log('res', res);//获取原始文件的后缀名let originalFilename = res.fileNamelet suffix = originalFilename.substring(originalFilename.lastIndexOf("."))const strdate = this.$dayjs().format('YYYY-MM-DD')const filename = `用户表导出-${strdate}${suffix}`//执行a标签下载downFile(res.data, filename)})},
downFile参考:
// 把后端二进制文件ArrayBuffer下载下来export function downFile(arrayBuffer, filename) {// 创建一个临时<a>标签const link = document.createElement('a')// 隐藏<a>标签link.style.display = 'none'// <a>标签href赋值link.href = window.URL.createObjectURL(new Blob([arrayBuffer]))// 设置下载文件名称link.download = filename// 追加在body元素里document.body.appendChild(link)// 调用单击事件,这里就会触发url下载功能link.click()// 移除之前创建的<a>标签document.body.removeChild(link)}
