asp.net导出到excel

时间:2014-09-03 12:02:05

标签: asp.net excel gridview

你好我有2页导出到excel,我使用这样的东西:

      Response.ClearContent()
            Response.Buffer = True
            Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "poView.xls"))
            Response.ContentEncoding = Encoding.UTF8
            Response.ContentType = "application/ms-excel"
            Dim tw As New IO.StringWriter()
            Dim htw As New HtmlTextWriter(tw)
            budgetPlanGrid.RenderControl(htw)
            Response.Write(tw.ToString())
            Response.[End]()

现在我确实设法导出到excel并查看所需的网格,但是在更复杂的页面上,由于某些原因,在gridview旁边有更多的东西,我从主页面看到了部分内容!并且它向我大喊我错过了我的style.css的路径,这与我试图导出的gridview无关! 我使用2个面板来使所有内容直到/ gridview visible = false, 我有点无能为力。

我希望在使用此代码时可能有人遇到过这类问题,并可以就如何寻找建议我?  先谢谢!

1 个答案:

答案 0 :(得分:0)

我在使用RenderControl时遇到了这个问题 - 一直在寻找丢失的样式表和其他废话。

我使用了用于绑定gridview的数据表并执行了此操作:

HttpContext.Current.Response.Clear();
HttpContacts.Current.Response.AddHeader("content-disposition", attachment):
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

string sTab = "";

foreach (DataColumn dc in dt.Columns)
{
HttpContext.Current.Response.Write(sTab + dc.ColumnName);
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");

int i;
foreach (DataRow dr in dt.Rows)
{
sTab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write(sTab + dr[i].ToString());
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
}

HttpContext.Current.Response.End();