.NET后端返回File文件,及前端处理直接在浏览器下载

本文介绍了如何使用C#后端代码实现将数据导出为Excel文件,并通过XMLHttpRequest与前端进行交互,实现文件的浏览器下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端代码

        [AllowAnonymous]
        public System.Web.Mvc.ActionResult ExportByteExcel(string datatab, string columnnames, string schemecode)
        {

            返回excel。
            string ReportName = "ExcelTemplete" + DateTime.Now.Ticks.ToString();
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("sheet1");

            int count = 0;
            // 生成标题行
            IRow row = sheet.CreateRow(count++);
            int headerIndex = 0;
            foreach (string columnName in newheads.Keys)
            {
                row.CreateCell(headerIndex++).SetCellValue(newheads[columnName]);
            }
            //生成数据
            foreach (Dictionary<string, object> data2 in datas)
            {
                row = sheet.CreateRow(count++);
                int bodyIndex = 0;
                foreach (string key in newheads.Keys)
                {
                    row.CreateCell(bodyIndex++).SetCellValue(data2[key] != null ? data2[key].ToString() : "");
                }
            }

            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            ms.Position = 0;

            string strPath = System.Web.HttpContext.Current.Server.MapPath("~/TempImages/");
            string strExcelFile = strPath + ReportName + ".xls";
            FileStream OutFile = new FileStream(strExcelFile, FileMode.Create, FileAccess.Write);
            byte[] btArray = ms.ToArray();
            OutFile.Write(btArray, 0, btArray.Length);
            OutFile.Flush();
            OutFile.Close();

            //object FileUrl = ExportExcel.ExportTempExecl("ExcelTemplete" + DateTime.Now.Ticks.ToString(), newheads, datas);

            //修改utf8编码,不然可能汉字会乱码
            string encodedFileName = System.Web.HttpUtility.UrlEncode((ReportName + ".xls").Replace("/", ""), System.Text.Encoding.UTF8);
            var contentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = encodedFileName
            };
            Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
            var contentType = "application/octet-stream";
            Response.Headers.Add("Content-Type", contentType);
            return File(btArray, contentType); 
        }

前端代码直接在浏览器下载:

var xhr = new XMLHttpRequest();
                        xhr.open("POST", "/portal/TXEmail/ExportByteExcel?datatab=" + encodeURIComponent(data.datatab) + "&columnnames=" + data.columnnames + "&schemecode=" + data.schemecode, true);
                        xhr.responseType = "blob";
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === XMLHttpRequest.DONE) {
                                if (xhr.status === 200) {
                                    //获取header中的内容
                                    var contentDispositionHeader = xhr.getResponseHeader('Content-Disposition');
                                    var fileName = contentDispositionHeader ? contentDispositionHeader.split('filename=')[1] : 'default_filename.xls';
                                    //需要对汉字编码否则会可能会乱码
                                    var decodedFileName = decodeURIComponent(fileName);
                                    // 创建Blob对象
                                    var blob = new Blob([xhr.response], { type: 'application/octet-stream' });
                                    // 创建临时URL并分配给一个链接
                                    var url = window.URL.createObjectURL(blob);
                                    var a = document.createElement('a');
                                    a.href = url;
                                    a.download = decodedFileName;
                                    document.body.appendChild(a);
                                    a.click();
                                } else {
                                    console.error("Error:", xhr.statusText);
                                }

                                
                            }
                        };
                        xhr.send();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值