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);
    });
相关推荐
x-cmd3 分钟前
[250512] Node.js 24 发布:ClangCL 构建,升级 V8 引擎、集成 npm 11
前端·javascript·windows·npm·node.js
小声读源码4 分钟前
【技巧】使用UV创建python项目的开发环境
开发语言·python·uv·dify
yxc_inspire11 分钟前
基于Qt的app开发第七天
开发语言·c++·qt·app
zm-v-1593043398612 分钟前
解锁遥感数据密码:DeepSeek、Python 与 OpenCV 的协同之力
开发语言·python·opencv
夏之小星星16 分钟前
el-tree结合checkbox实现数据回显
前端·javascript·vue.js
周Echo周25 分钟前
20、map和set、unordered_map、un_ordered_set的复现
c语言·开发语言·数据结构·c++·算法·leetcode·list
明天更新30 分钟前
Java处理压缩文件的两种方式!!!!
java·开发语言·7-zip
crazyme_630 分钟前
前端自学入门:HTML 基础详解与学习路线指引
前端·学习·html
老胖闲聊36 分钟前
C# 注册表操作类
开发语言·c#
勘察加熊人38 分钟前
Python+Streamlit实现登录页
开发语言·python