首页 > 其他 > 详细

将list导出成Excel到浏览器

时间:2021-04-23 16:32:25      阅读:19      评论:0      收藏:0      [点我收藏+]
            System.Data.DataTable dtSource = ToDataTable<EmpExtension>(empList);

            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = Encoding.UTF8;
            Response.Charset = "";
            Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + strFileName);  //路径:HttpUtility.UrlEncode(strFileName, Encoding.UTF8)

            XlsDocument xls = new XlsDocument();
            Worksheet sheet = xls.Workbook.Worksheets.Add(strFileName);


            if (dtSource == null || dtSource.Rows.Count == 0) { return; }
            //XlsDocument xls = new XlsDocument();
            //Worksheet sheet = xls.Workbook.Worksheets.Add(sheetName);

            //填充表头  
            foreach (DataColumn col in dtSource.Columns)
            {
                sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName);
            }

            //填充内容  
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    sheet.Cells.Add(i + 2, j + 1, dtSource.Rows[i][j].ToString());
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                xls.Save(ms);
                ms.Flush();
                ms.Position = 0;
                sheet = null;
                xls = null;
                HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();

                response.Charset = "UTF-8";
                response.ContentType = "application/vnd.ms-excel";//"application/vnd.ms-excel";
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + strFileName));
                //System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);
                byte[] data = ms.ToArray();
                System.Web.HttpContext.Current.Response.BinaryWrite(data);

            }

这里使用到了MyXls

然后前端直接使用

window.open("........")

即可

将list导出成Excel到浏览器

原文:https://www.cnblogs.com/AduBlog/p/14692626.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!