我编写了一个代码来将gridview提取到Excel。除了gridview中的一行外,一切正常。当我将gridview导出到excel时,最后一行不包含在excel文件中。当我扫描我的整个代码时,我发现了一个创建问题的代码。这是代码:
protected void OnDataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "A";
cell.ColumnSpan = 9;
row.Controls.Add(cell);
gv.HeaderRow.Parent.Controls.AddAt(0, row);
}
此代码用于向合并单元格的gridview添加新标头。删除此代码后,一切正常。但我需要那些代码。
导出到Excel代码:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Rept" + DateTime.Now.ToString("yyyy_MM_ddThh_mm_ss_") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(gvpanel);
form.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
如何解决这个问题?
答案 0 :(得分:1)
我无法在任何地方找到解决方案,这使我能够提供此解决方案。 当您创建标题行&你也需要导出到excel,下面的代码解决了错过最后一行的问题。
使用RowCreated事件创建动态标题行。
protected void Grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell1 = new TableCell();
HeaderCell1.Text = "Solved your Issue";
HeaderCell1.ColumnSpan = 10;
HeaderRow.Cells.Add(HeaderCell1);
Grid.Controls[0].Controls.Add(HeaderRow);
}
}
现在您可以调用ExportToExcel方法:
private void ExportToExcel(GridView gv, string exportfilename)
{
string filename = exportfilename + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
gv.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.Flush();
Response.End();
}
答案 1 :(得分:0)
您可以使用Excel电子表格作为GridView的数据源,并像其他任何数据库一样连接到它:
How To Query and Display Excel Data by Using ASP.NET, ADO.NET, and Visual Basic .NET