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);
    });
相关推荐
李宥小哥2 小时前
C#基础11-常用类
android·java·c#
北海-cherish2 小时前
vue中的 watchEffect、watchAsyncEffect、watchPostEffect的区别
前端·javascript·vue.js
C嘎嘎嵌入式开发2 小时前
(2)100天python从入门到拿捏
开发语言·python
Stanford_11063 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
2501_915909063 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
Vallelonga4 小时前
Rust 中的数组和数组切片引用
开发语言·rust
Kiri霧4 小时前
Rust模式匹配详解
开发语言·windows·rust
偶尔的鼠标人4 小时前
Avalonia中,使用DataTable类型作为DataGrid的ItemSource 数据源
ui·c#·avalonia
white-persist4 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
千里马-horse4 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner