导出Grid的数据(全部)到Excel
[C#] 纯文本查看 复制代码 /// <summary>
/// 导出Grid的数据(全部)到Excel
/// 字段全部为BoundField类型时可用
/// 要是字段为TemplateField模板型时就取不到数据
/// </summary>
/// <param name="grid">grid的ID</param>
/// <param name="dt">数据源</param>
/// <param name="excelFileName">要导出Excel的文件名</param>
public static void OutputExcel(GridView grid, DataTable dt, string excelFileName)
{
Page page = (Page)HttpContext.Current.Handler;
page.Response.Clear();
string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));
page.Response.AddHeader("Content-Disposition", "attachment:filename=" + fileName + ".xls");
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.Charset = "utf-8";
StringBuilder s = new StringBuilder();
s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");
int count = grid.Columns.Count;
s.Append("<table border=1>");
s.AppendLine("<tr>");
for (int i = 0; i < count; i++)
{
if (grid.Columns.GetType() == typeof(BoundField))
[i] s.Append("<td>" + grid.Columns.HeaderText + "</td>");
//s.Append("<td>" + grid.Columns.HeaderText + "</td>");
}
s.Append("</tr>");
foreach (DataRow dr in dt.Rows)
{
s.AppendLine("<tr>");
for (int n = 0; n < count; n++)
{
if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>");
}
s.AppendLine("</tr>");
}
s.Append("</table>");
s.Append("</body></html>");
page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));
page.Response.End();
}
其实这个是一个比较简单的方法,而且百度上也会有很多,但是我这个方法的好处就是我一直在用,而且解决了不少Bug
贴出来,有用的拿 去
|