C# 将用户控件gridview导出到excel
在我的aspx页面上,我有一个C# 将用户控件gridview导出到excel,c#,asp.net,excel,gridview,C#,Asp.net,Excel,Gridview,在我的aspx页面上,我有一个Usercontrol,其中包含一个Gridview,它的数据根据从aspx页面传递到Usercontrol的参数动态加载,我称之为QuotesReport1 当导出运行时,它只将布局导出到电子表格中,而不导出gridview的任何数据,例如: 在UserControl内部运行SQL查询,该查询返回一个DataTable,然后将其绑定到UserControl内部的Gridview,如下所示: SQLData da = new SQLData(); GridView
Usercontrol
,其中包含一个Gridview
,它的数据根据从aspx页面传递到Usercontrol的参数动态加载,我称之为QuotesReport1
当导出运行时,它只将布局导出到电子表格中
,而不导出gridview的任何数据,例如:
在UserControl内部运行SQL查询,该查询返回一个DataTable,然后将其绑定到UserControl内部的Gridview,如下所示:
SQLData da = new SQLData();
GridView1.DataSource = da.SGetDataTable(query);
GridView1.DataBind();
我所拥有的最简单的方法
public class ExcelUtility
{
public static void ToExcel(object dataSource)
{
GridView grid = new GridView { DataSource = dataSource };
grid.DataBind();
StringBuilder sb = new StringBuilder();
foreach (TableCell cell in grid.HeaderRow.Cells)
sb.Append(string.Format("\"{0}\",", cell.Text));
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
foreach (GridViewRow row in grid.Rows)
{
foreach (TableCell cell in row.Cells)
sb.Append(string.Format("\"{0}\",", cell.Text.Trim().Replace(" ", string.Empty)));
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
}
ExportToExcel(sb.ToString());
}
private static void ExportToExcel(string data)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.csv");
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(data);
HttpContext.Current.Response.End();
}
}
使用:
string result = ExcelUtility.ToExcel(_db.FindAll());
ExcelUtility.ExportToExcel(result);
在将数据写入excel工作表之前,请绑定网格。绑定网格视图的代码在哪里?请将该代码粘贴到原始问题中。。注释部分的格式很难阅读…Thanx@DJKRAZE,我已经相应地更新了。只是一个简单的问题,网格是否实际显示了任何数据。。?您是否已在Page_Load事件中遍历代码,并在UserControl所在的代码中放置断点。。?
public class ExcelUtility
{
public static void ToExcel(object dataSource)
{
GridView grid = new GridView { DataSource = dataSource };
grid.DataBind();
StringBuilder sb = new StringBuilder();
foreach (TableCell cell in grid.HeaderRow.Cells)
sb.Append(string.Format("\"{0}\",", cell.Text));
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
foreach (GridViewRow row in grid.Rows)
{
foreach (TableCell cell in row.Cells)
sb.Append(string.Format("\"{0}\",", cell.Text.Trim().Replace(" ", string.Empty)));
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
}
ExportToExcel(sb.ToString());
}
private static void ExportToExcel(string data)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.csv");
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(data);
HttpContext.Current.Response.End();
}
}
string result = ExcelUtility.ToExcel(_db.FindAll());
ExcelUtility.ExportToExcel(result);