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);
    });
相关推荐
Lyyaoo.1 小时前
【JAVA基础面经】JVM的内存模型
java·开发语言·jvm
杨凯凡1 小时前
【017】泛型与通配符:API 设计里怎么用省心
java·开发语言
还有你Y5 小时前
Shell 脚本语法
前端·语法·sh
踩着两条虫7 小时前
如何评价VTJ.PRO?
前端·架构·ai编程
2401_873479408 小时前
如何利用IP查询定位识别电商刷单?4个关键指标+工具配置方案
开发语言·tcp/ip·php
Mh8 小时前
鼠标跟随倾斜动效
前端·css·vue.js
我爱cope8 小时前
【从0开始学设计模式-10| 装饰模式】
java·开发语言·设计模式
rockey6278 小时前
AScript函数体系详解
c#·.net·script·eval·expression·function·动态脚本
菜鸟学Python8 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
小码哥_常9 小时前
Kotlin类型魔法:Any、Unit、Nothing 深度探秘
前端