从Gridview Data导出到Excel

时间:2013-07-23 07:56:20

标签: c# nullreferenceexception

我正在使用Windows窗体应用程序。我想使用SaveAs(浏览)选项将我的gridview数据导出为ex​​cel。

请建议。

5 个答案:

答案 0 :(得分:3)

这意味着当前HttpContextHttpContext.Current)为null

这是因为这是一个Windows窗体应用程序,而不是一个ASP.NET网站。你不能这样做。

答案 1 :(得分:3)

Windows窗体应用程序中没有HttpContext,因此在您的情况下为空

答案 2 :(得分:3)

HttpContext.Current仅对于Web应用程序不为null。在Windows应用程序中,它始终为空。

答案 3 :(得分:2)

HttpContextHttpContext.Current似乎是空的。

答案 4 :(得分:1)

您可以使用此代码进行导出,因为您使用的是用于导出asp.net网格视图的代码:

public void export_datagridview_to_excel(DataGridView dgv, string excel_file)
{
    int cols;
    //open file
    StreamWriter wr = new StreamWriter(excel_file);
    //determine the number of columns and write columns to file
    cols = dgv.Columns.Count;
    for (int i = 0; i < cols; i++)
    {
        wr.Write(dgv.ColumnsIdea.Name.ToString().ToUpper() + "\t");
    }
    wr.WriteLine();
    //write rows to excel file
    for (int i = 0; i < (dgv.Rows.Count - 1); i++)
    {
        for (int j = 0; j < cols; j++)
        {
            if (dgv.RowsIdea.Cells[j].Value != null)
                wr.Write(dgv.RowsIdea.Cells[j].Value + "\t");
            else
            {
                wr.Write("\t");
            }
        }
        wr.WriteLine();
    }
    //close file
    wr.Close();
}