当前位置:编程学习 > C#/ASP.NET >>

一个下载文件的问题,各位帮忙看下。。。急急急

需求:将数据导入到Excel里,并下载。

问题所在:在IE下,会下载当前页面的源代码。看图:


火狐下正常,看图:


代码:
        /// <summary>
        /// 数据导出到Excel 
        /// </summary>
        /// <param name="table">数据表</param>
        /// <param name="context">上下文对象</param>
        /// <param name="fileName">文件名</param>
        public static void RenderToExcelBrowser(DataTable table, HttpContext context, string fileName)
        {
            MemoryStream ms = new MemoryStream();
            using (table)
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);              
                foreach (DataColumn column in table.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);

                // handling value.
                int rowIndex = 1;
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in table.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }
                    rowIndex++;
                }
                workbook.Write(ms);
                ms.Flush();
            }//.xlsx
            fileName=fileName+"-"+ DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";  

            context.Response.ContentType = "application/octet-stream";
            context.Response.AddHeader("Content-Disposition", "attachement;filename=" + fileName);
            context.Response.AddHeader("Content-Length", ms.ToArray().Length.ToString()); 
        
            //context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
            //System.Web.HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());
            context.Response.BinaryWrite(ms.ToArray());
        }
Excel 火狐 下载 asp.net .net
补充:.NET技术 ,  .NET技术前瞻
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,