从gridview导出到Excel

时间:2010-06-24 11:44:46

标签: c# asp.net gridview export-to-excel

我有导出到Excel的代码。在我的gridview中,我设置了分页以显示pagecount中的记录数。

但是在导出到Excel时,它并没有给我整个记录,而是向我展示了六条记录的相同分页。

我的代码:

string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

// Create a form to contain the grid
HtmlForm frm = new HtmlForm();

GrdDynamicControls.AllowPaging = false;
GrdDynamicControls.Parent.Controls.Add(frm);

frm.Attributes["runat"] = "server";
frm.Controls.Add(GrdDynamicControls);
frm.RenderControl(htw);

//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

如何更改或禁用分页以从gridview获取所有记录?

我在gridview中的数字为+ 9199等,但在导出后它会以9.99等格式显示它。

如何从这里传递数字格式?

3 个答案:

答案 0 :(得分:1)

我不熟悉ASP.NET,但我相信您将一些数据源(dataTable或List<>)绑定到您的网格。导出数据源而不是dataGrid。

答案 1 :(得分:1)

您可以将gridview数据源(例如,数据集)导出到Excel。

以下是执行此操作的示例代码。您可以参考 Howto: Export a dataset to Excel (C# / ASP.NET) 获取更多信息。

using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Whatever
{
    ///
    /// This class provides a method to write a dataset to the HttpResponse as
    /// an Excel file.
    ///
    public class ExcelExport
    {
        public static void ExportDataSetToExcel(DataSet ds, string filename)
        {
            HttpResponse response = HttpContext.Current.Response;

            // First let's clean up the response.object.
            response.Clear();
            response.Charset = "";

            // Set the response mime type for Excel.
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

            // Create a string writer.
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // Instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = ds.Tables[0];
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }
        }
    }
}

答案 2 :(得分:0)

我认为在禁用分页以获取所有记录后,您需要重新绑定网格。

我也赞同奥索尔的评论;而不是导出网格中的内容;导出数据源。