将网格数据转换为Excel时出错

时间:2009-03-26 15:05:14

标签: c# .net asp.net excel gridview

这是代码:

TextWriter writer = null;

HttpResponse response = new HttpResponse(writer);

response.ClearContent();
response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
// response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
HtmlForm htmlForm = new HtmlForm();
GridView1.Parent.Controls.Add(htmlForm);
htmlForm.Attributes["runat"] = "server";
htmlForm.Controls.Add(GridView1);
htmlForm.RenderControl(htmlTextWriter);

response.Write(stringWriter.ToString());

如果我运行此代码,则会抛出NullReferenceException。我在业务逻辑层中使用了这些代码

1 个答案:

答案 0 :(得分:2)

当您点击response.Write行时收到运行时错误,因为您将null作为响应流传递:

TextWriter writer = null;
HttpResponse response = new HttpResponse(writer);

您发布的代码非常草率。我建议你从头开始重写方法。如果你不这样做,你可能会遇到其他运行时错误。