在开发中导出Excel是一个很常见也很简单的功能,通过vue脚手架实现这个功能在网上也有好多教程,大部分写的都没有问题,我只简单的总结下:

  axios({
        method: 'GET',
        url: '/api',
        params: params,
        responseType: 'blob'
      }).then(res=>{
        let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
        let url = window.URL.createObjectURL(blob);
        window.location.href = url;
      }).catch(err=>{
        console.log(err)
      })

后台是通过C#提供的API实现的,就简单的返回一个数据流如下:

以下是后台的写法:

[HttpPost]
        public HttpResponseMessage ExportFile()
        {
	string filePath =@"D:\demo.xls";
var stream = new MemoryStream(File.ReadAllBytes(filePath));
            var resp = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content =  new StreamContent(stream)
        };

            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");

            resp.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8),
                DispositionType = "UTF-8"
            };
         
            return resp;
}

在经过数次尝试后得到如下结果:

这个问题困扰了好长一段时间,几经尝试也无法解决不了,最后经过仔细比对发现后台传过来的值到前端后发生了变化,通过排查发现竟是mock.js引起的,它把所有的请求和响应,注意是所有的,不管符合不符合规则都拦截重新写了,这个本来就是为了测试才引入的,所以把它去掉就可以了。

去掉mock可以参考这里:https://lebang2020.cn/details/201121yzknaesk.html

相关文章:Vue axios 下载文件