C# Web API下基于axios的xlsx文件下载

服务端代码基于miniexcel库开发

C# 复制代码
MemoryStream memoryStream = new MemoryStream();
memoryStream.SaveAs(stations.ToList());
memoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
    FileDownloadName = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}.xlsx"
};

前端代码

JS 复制代码
axios.create({
    baseURL: 'https://localhost:7189/',
    timeout: 2000,
    headers: {
        'Content-Type': 'application/json'
    }
}).post("/tablestation", {
        startTime: startTime.value,
        endTime: endTime.value,
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        selectionMode: 1
    }, {
        responseType: 'blob',
    }).then((response) => {
        // 通过正则表达式获取下载文件名称
	    var filename = '';
	    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
	    var matches = filenameRegex.exec(response.headers['content-disposition']);
	    if (matches != null && matches[1]) {
	        filename = matches[1].replace(/['"]/g, '');
	    }
	
	    // 使用blob进行文件下载
	    var blob = new Blob([response.data], { type: response.headers['content-type'] });
	    if ('msSaveOrOpenBlob' in navigator) {
	        window.navigator.msSaveOrOpenBlob(blob, filename);
	    } else {
	        const link = document.createElement('a');
	        link.href = window.URL.createObjectURL(blob);
	        link.setAttribute('download', filename);
	        document.body.appendChild(link);
	        link.click();
	        window.URL.revokeObjectURL(link.href);
	        document.body.removeChild(link);
	    }
    })
    .catch(function (error) {
        console.log(error);
    });
相关推荐
曹牧3 分钟前
Spring Boot:如何在Java Controller中处理POST请求?
java·开发语言
浅念-6 分钟前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
WeiXiao_Hyy7 分钟前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
User_芊芊君子13 分钟前
CANN010:PyASC Python编程接口—简化AI算子开发的Python框架
开发语言·人工智能·python
kylezhao201916 分钟前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk20 分钟前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
Max_uuc23 分钟前
【C++ 硬核】打破嵌入式 STL 禁忌:利用 std::pmr 在“栈”上运行 std::vector
开发语言·jvm·c++
吃杠碰小鸡24 分钟前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨24 分钟前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
牵牛老人27 分钟前
【Qt 开发后台服务避坑指南:从库存管理系统开发出现的问题来看后台开发常见问题与解决方案】
开发语言·qt·系统架构