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);
    });
相关推荐
whm2777几秒前
Visual Basic 值传递与地址传递
java·开发语言·数据结构
CoderYanger5 分钟前
前端基础——HTML练习项目:填写简历信息
前端·css·职场和发展·html
CodeCraft Studio8 分钟前
国产化PDF处理控件Spire.PDF教程:如何在 C# 中从 HTML 和 PDF 模板生成 PDF
pdf·c#·html·.net·spire.pdf·pdf文档开发·html创建模板pdf
muyouking1110 分钟前
深入理解 HTML `<label>` 的 `for` 属性:提升表单可访问性与用户体验
前端·html·ux
CHANG_THE_WORLD10 分钟前
c语言位运算 汇编代码分析
c语言·开发语言·汇编
x_feng_x21 分钟前
Java从入门到精通 - 集合框架(二)
java·开发语言·windows
IT_陈寒31 分钟前
Java性能调优:从GC日志分析到实战优化的5个关键技巧,让你的应用快如闪电!
前端·人工智能·后端
Le1Yu32 分钟前
雪崩问题及其解决方案(请求限流、线程隔离、服务熔断、fallback、sentinel实现以上功能)
java·开发语言
Mintopia37 分钟前
🚀 Next.js API 压力测试:一场前端与后端的“极限拉扯”
前端·后端·全栈
Mintopia41 分钟前
🛡️ 对抗性攻击与防御:WebAI模型的安全加固技术
前端·javascript·aigc