前端vue后端java使用easyexcel框架下载表格xls数据工具类

一 使用alibaba开源的 easyexcel框架,后台只需一个工具类即可实现下载

后端下载实现

依赖 pom.xml
XML 复制代码
 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.0</version>
        </dependency>
后台JAVA代码
java 复制代码
/**
     * 下载xls数据
     * @param params
     * @param response
     * @throws IOException
     */
    @PostMapping("/exportData")
    public void exportData(@RequestBody String params, HttpServletResponse response) throws IOException {
        JSONObject query = JSONObject.parseObject(params);


        String beginTime = query.getString("beginDate");
        String endTime = query.getString("endDate");

        List<AliIotLog> resultList = new ArrayList<>();
        
        //查询业务数据列表  resultList 

        WebDownloadUtil.downloadXlsByList(response, resultList,LogExport.class,"xls");
    }

一个 java bean代码,用于设置导出时的列映射显示名称关系

java 复制代码
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import java.io.Serializable;
import java.time.LocalDateTime;


@ContentRowHeight(20)//注解用于指定某元素的内容行高度为20。
@HeadRowHeight(20)//注解用于指定某元素的表头行高度为20。
@ColumnWidth(30) //注解用于指定某元素的列宽度为30。
public class LogExport implements Serializable {

    private static final long serialVersionUID = 1L;

            /**
            * 设备协议内容
            */
            @ExcelProperty("接收报文")
            private String inHexStr;

            /**
            * 回复内容
            */
            @ExcelProperty("发送报文")
            private String outHexStr;

            /**
            * 地址或通道
            */
            @ExcelProperty("地址")
            private String addr;


            /**
            * 时间
            */
            @ExcelProperty("时间")
            private LocalDateTime ctime;



        public String getInHexStr() {
        return inHexStr;
        }

            public void setInHexStr(String inHexStr) {
        this.inHexStr = inHexStr;
        }
        public String getOutHexStr() {
        return outHexStr;
        }

            public void setOutHexStr(String outHexStr) {
        this.outHexStr = outHexStr;
        }
        public String getAddr() {
        return addr;
        }

            public void setAddr(String addr) {
        this.addr = addr;
        }

        public LocalDateTime getCtime() {
        return ctime;
        }

            public void setCtime(LocalDateTime ctime) {
        this.ctime = ctime;
        }



}
完整下载工具类代码
java 复制代码
/**
 * web 下载文件封装
 * @author hua
 * @date 2024-07-06 14:30
 */
public class WebDownloadUtil {


    /**
     * 下载文件
     * @param response
     * @param resultList 列表数据
     * @param clazz 类形
     * @param format 表格格式 xlx xlsx csv
     * @throws IOException
     */
    public static void downloadXlsByList(HttpServletResponse response, List resultList,Class clazz,String format) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-disposition","attachment;filename=data_export.xls");//下载文件名称在前端vue页面处理

        ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.CSV;

        if("xls".equals(format)){
            excelTypeEnum = ExcelTypeEnum.XLS;
        }else if("xlsx".equals(format)){
            excelTypeEnum = ExcelTypeEnum.XLSX;
        }


        ExcelWriterBuilder writeWork = EasyExcel.write(response.getOutputStream(),clazz  ).excelType(excelTypeEnum).registerConverter(new Converter<LocalDateTime>(){
            public String format = "yyyy-MM-dd HH:mm:ss";

            @Override
            public Class<LocalDateTime> supportJavaTypeKey() {
                return LocalDateTime.class;
            }

            @Override
            public CellDataTypeEnum supportExcelTypeKey() {
                return CellDataTypeEnum.STRING;
            }

            @Override
            public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
                return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(format)).atStartOfDay();
            }

            @Override
            public WriteCellData<?> convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
                if(localDateTime==null){
                    return new WriteCellData<>("");
                }
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
                String format = formatter.format(localDateTime);
                return new WriteCellData(format);
            }

        });

        ExcelWriterSheetBuilder sheet = writeWork.sheet();
        sheet.doWrite(resultList);
    }
}

前端vue下载实现

vue前端页下载调用按钮
javascript 复制代码
   import webUtil from "@api/webUtil";


export default {
 
  name: 'sys_log',
  data () {
    return {
    queryBody:{},
    list:[],
}

methods: {
            exportExcel () {
                //单击下载
                console.log('query data',this.queryBody)
                let url='/xxx/xxx/xxxx';
                webUtil.downloadXls(url,this.queryBody,"导出数据")

            }
         }

}
vue 完整下载工具类
javascript 复制代码
import request from '@/plugins/request';

const webUtil= {

    downloadXls:function(url,data, fileNamePrefix){
            request({
                url: url,
                method: 'post',
                responseType: "blob",
                data
            }).then(data => {
                let blob = new Blob([data], {
                    type: 'application/x-msdownload;charset=UTF-8'
                });
                let fileName = fileNamePrefix + Date.parse(new Date()) + '.xls';
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName);
                } else {
                    let link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
                    link.click();
                    window.URL.revokeObjectURL(link.href);
                }
            }).catch(error => {
                console.error('Error exporting and downloading data:', error);
            }));

    }


};
export default webUtil;
最终下载效果。
相关推荐
2601_94981792几秒前
spring-ai 下载不了依赖spring-ai-openai-spring-boot-starter
java·人工智能·spring
九皇叔叔几秒前
006-SpringSecurity-Demo 跨域(CORS)配置
java·springboot3·springsecurity·跨域·cors
格林威5 分钟前
ZeroMQ 在视觉系统中的应用
开发语言·人工智能·数码相机·机器学习·计算机视觉·c#·视觉检测
safestar20128 分钟前
React 19实战:Action、并发与性能,一次告别“意大利面状态”的升级
开发语言·javascript·vue.js
迷藏49415 分钟前
**发散创新:基于Python与深度学习的情绪识别实战全流程解析**在人工智能快速发展的今天,**情绪识别(Emoti
java·人工智能·python·深度学习
Ashore11_17 分钟前
蓝桥杯16届Java研究生组
java·算法·蓝桥杯
一只幸运猫.17 分钟前
Rust实用工具特型-Clone
开发语言·后端·rust
东离与糖宝20 分钟前
Spring AI 2.0+Gemma 4端侧部署:Java离线AI应用全教程
java·人工智能
0xDevNull29 分钟前
Java BigDecimal 完全指南:从入门到精通
java·开发语言·后端
桌面运维家29 分钟前
交换机环路排查:STP配置实战与网络故障精确定位
开发语言·php