将 Datagrid 导出到 excel asp

发布于 2024-07-08 04:45:03 字数 162 浏览 9 评论 0原文

将 Datagrid 导出到 Excel 的最佳方法是什么? 我没有任何将数据网格导出到Excel的经验,所以我想知道你们如何将数据网格导出到Excel。 我读到有很多方法,但我想只是做一个简单的导出 excel 到 datagrid 函数。我正在使用 asp.net C#

欢呼..

whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#

cheers..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无言温柔 2024-07-15 04:45:03

最简单的方法是简单地编写 csv 或 html(特别是 ...

...

...< /table>) 到输出,并通过内容类型标头简单地假装它是 Excel 格式。 Excel 会很乐意加载其中任何一个; csv 更简单...

...

这是一个类似的示例(它实际上需要一个 IEnumerable,但它与任何源都类似(例如 DataTable,循环遍历行)。

        public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (string.IsNullOrEmpty(filename)) filename = "export.csv";

            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.Clear();
            // remove this line if you don't want to prompt the user to save the file
            resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            // if not saving, try: "application/ms-excel"
            resp.ContentType = "text/csv";
            string csv = GetCsv(headers, data);
            byte[] buffer = resp.ContentEncoding.GetBytes(csv);
            resp.AddHeader("Content-Length", buffer.Length.ToString());
            resp.BinaryWrite(buffer);
            resp.End();
        }
        static void WriteRow(string[] row, StringBuilder destination)
        {
            if (row == null) return;
            int fields = row.Length;
            for (int i = 0; i < fields; i++)
            {
                string field = row[i];
                if (i > 0)
                {
                    destination.Append(',');
                }
                if (string.IsNullOrEmpty(field)) continue; // empty field

                bool quote = false;
                if (field.Contains("\""))
                {
                    // if contains quotes, then needs quoting and escaping
                    quote = true;
                    field = field.Replace("\"", "\"\"");
                }
                else
                {
                    // commas, line-breaks, and leading-trailing space also require quoting
                    if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
                        || field.StartsWith(" ") || field.EndsWith(" "))
                    {
                        quote = true;
                    }
                }
                if (quote)
                {
                    destination.Append('\"');
                    destination.Append(field);
                    destination.Append('\"');
                }
                else
                {
                    destination.Append(field);
                }

            }
            destination.AppendLine();
        }
        static string GetCsv(string[] headers, IEnumerable<string[]> data)
        {
            StringBuilder sb = new StringBuilder();
            if (data == null) throw new ArgumentNullException("data");
            WriteRow(headers, sb);
            foreach (string[] row in data)
            {
                WriteRow(row, sb);

            }
            return sb.ToString();
        }

The simplest way is to simply write either csv, or html (in particular, a <table><tr><td>...</td></tr>...</table>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...

Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a DataTable, looping over the rows).

        public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (string.IsNullOrEmpty(filename)) filename = "export.csv";

            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.Clear();
            // remove this line if you don't want to prompt the user to save the file
            resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            // if not saving, try: "application/ms-excel"
            resp.ContentType = "text/csv";
            string csv = GetCsv(headers, data);
            byte[] buffer = resp.ContentEncoding.GetBytes(csv);
            resp.AddHeader("Content-Length", buffer.Length.ToString());
            resp.BinaryWrite(buffer);
            resp.End();
        }
        static void WriteRow(string[] row, StringBuilder destination)
        {
            if (row == null) return;
            int fields = row.Length;
            for (int i = 0; i < fields; i++)
            {
                string field = row[i];
                if (i > 0)
                {
                    destination.Append(',');
                }
                if (string.IsNullOrEmpty(field)) continue; // empty field

                bool quote = false;
                if (field.Contains("\""))
                {
                    // if contains quotes, then needs quoting and escaping
                    quote = true;
                    field = field.Replace("\"", "\"\"");
                }
                else
                {
                    // commas, line-breaks, and leading-trailing space also require quoting
                    if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
                        || field.StartsWith(" ") || field.EndsWith(" "))
                    {
                        quote = true;
                    }
                }
                if (quote)
                {
                    destination.Append('\"');
                    destination.Append(field);
                    destination.Append('\"');
                }
                else
                {
                    destination.Append(field);
                }

            }
            destination.AppendLine();
        }
        static string GetCsv(string[] headers, IEnumerable<string[]> data)
        {
            StringBuilder sb = new StringBuilder();
            if (data == null) throw new ArgumentNullException("data");
            WriteRow(headers, sb);
            foreach (string[] row in data)
            {
                WriteRow(row, sb);

            }
            return sb.ToString();
        }
尾戒 2024-07-15 04:45:03

您可以通过以下方式完成此操作:

private void ExportButton_Click(object sender, System.EventArgs e)
{
  Response.Clear();
  Response.Buffer = true;
  Response.ContentType = "application/vnd.ms-excel";
  Response.Charset = "";
  this.EnableViewState = false;
  System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
  this.ClearControls(dataGrid);
  dataGrid.RenderControl(oHtmlTextWriter);
  Response.Write(oStringWriter.ToString());
  Response.End();
}

此处完成示例。

You can do it in this way:

private void ExportButton_Click(object sender, System.EventArgs e)
{
  Response.Clear();
  Response.Buffer = true;
  Response.ContentType = "application/vnd.ms-excel";
  Response.Charset = "";
  this.EnableViewState = false;
  System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
  this.ClearControls(dataGrid);
  dataGrid.RenderControl(oHtmlTextWriter);
  Response.Write(oStringWriter.ToString());
  Response.End();
}

Complete example here.

残疾 2024-07-15 04:45:03

SpreadsheetGear for .NET 可以做到这一点。

您可以在此处查看带有 C# 和 VB 源代码的实时 ASP.NET 示例。 其中几个示例演示了将 DataSet 或 DataTable 转换为 Excel - 并且您可以轻松地从 DataGrid 获取 DataSet 或 DataTable。 如果您想亲自尝试,可以在此处下载免费试用版。

免责声明:我拥有 SpreadsheetGear LLC

SpreadsheetGear for .NET will do it.

You can see live ASP.NET samples with C# and VB source code here. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文