如何使用asp.net以excel格式下载SQL数据

By simon at 2018-02-28 • 0人收藏 • 32人看过

我试图以excel格式下载我的数据。以下代码完成这项工作 完美但格式出来被破坏。 尔我得到的ror - 文件格式和扩展名不匹配。该文件可以 被破坏或不安全。除非你相信它的来源,不要打开它。你做 想反正打开它?在确认是时,文件打开。 请看代码并帮助我站在我必须做出什么改变 (xls 97-2003 excel工作手册)下载我的数据。

 if (dt4.Rows.Count > 0)
        {
            string filename = "DownloadMobileNoExcel.xls";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt4;
            dgGrid.DataBind();

            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.
            //Response.ContentType = application/vnd.ms-excel;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());

1 个回复 | 最后更新于 2018-02-28
2018-02-28   #1

首先 下载[打开Xml](https://www.microsoft.com/en- in / download / details.aspx?id = 5124)下载[关闭 XML](https://开头存档.codeplex.com /?p = closedxml)库 导入这个命名空间

using System.IO;
using System.Data;
using ClosedXML.Excel;
using System.Configuration;
using System.Data.SqlClient;
试着这样做
 using (XLWorkbook wb = new XLWorkbook())
                        {
                            wb.Worksheets.Add(dt, "Customers");

                            Response.Clear();
                            Response.Buffer = true;
                            Response.Charset = "";
                            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                            Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
                            using (MemoryStream MyMemoryStream = new MemoryStream())
                            {
                                wb.SaveAs(MyMemoryStream);
                                MyMemoryStream.WriteTo(Response.OutputStream);
                                Response.Flush();
                                Response.End();
                            }
                        }

这里是Mudassar汗有一个很好的文章 [这里](https://www.aspsnippets.com/Articles/Export-data-from-SQL-Server-to- Excel的在-ASPNET-使用-C-和-VBNet.aspx)

登录后方可回帖

Loading...