【问题标题】:Creating Excel File from gridview从 gridview 创建 Excel 文件
【发布时间】:2016-06-23 11:39:07
【问题描述】:

这里我用 gridview 数据创建 excel 文件,代码如下

Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridView1.AllowPaging = false;           
            //Change the Header Row back to white color
            GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
            //Applying stlye to gridview header cells
            for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
            {
                GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
            }
            GridView1.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

它工作正常,但是如果我将 gridview 属性设置为 AllowPaging="true",则 excel 文件仅包含分页 1 数据,我如何将所有数据从 gridview 导出到 excel。

【问题讨论】:

  • 你把这个allowpaging保存在哪里?

标签: c# asp.net excel gridview


【解决方案1】:

在您的 aspx 页面中,设置网格的 AllowPaging="true"

在你的代码后面的文件中更改你的代码,

GridView1.AllowPaging = false;    
// BIND YOUR GRID HERE AGAIN

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

【讨论】:

    【解决方案2】:

    我假设您正在使用存储在 DataSetDataTableList&lt;&gt; 中的数据填充您的 GridView

    如果是这样,只需获取该变量,并将其传递给我的“导出到 Excel”C# 库,它就会为您创建一个真正的 .xlsx 文件,并且可以将它直接传递给您网页的Response

    class Employee;
    List<Employee> listOfEmployees = new List<Employee>();
    
    ...
    GridView1.DataSource = listOfEmployees;
    ...
    
    // The following ASP.Net code gets run when I click on my "Export to Excel" button.
    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        // It doesn't get much easier than this...
        CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
    }
    

    “导出到 Excel”类的完整源代码可以在这里找到:

    Export to Excel

    您不想这样做的唯一原因是,如果您特别希望您的 Excel 在通过 RowDataBound 函数修改后包含 GridView 中显示的值。

    我的建议是只导出绑定到 GridView 的原始数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-12
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多