如何将ASP.NET Linq绑定的GridView数据高效导出到Excel文件?
- 内容介绍
- 文章标签
- 相关推荐
本文共计578个文字,预计阅读时间需要3分钟。
您可以使用以下代码片段来仅导出GridView中的数据到Excel,而不是整个页面:
csharpHtmlForm form=new HtmlForm();Response.Clear();Response.Buffer=true;Response.ContentType=application/vnd.ms-excel;Response.AddHeader(Content-Disposition, attachment;filename=GridViewData.xlsx);Response.Charset=UTF-8;
StringBuilder sb=new StringBuilder();sb.Append();
// 假设GridView的名称为myGridViewGridView myGridView=(GridView)Page.FindControl(myGridView);foreach (GridViewRow row in myGridView.Rows){ sb.Append(); foreach (TableCell cell in row.Cells) { sb.AppendFormat({0}, cell.Text); } sb.Append();}
sb.Append();
Response.Write(sb.ToString());Response.End();
这段代码首先创建一个新的HtmlForm,然后清除响应并设置内容类型为Excel。接着,它遍历GridView的每一行和每一列,将数据格式化为HTML表格,并将表格内容写入响应流中,最后结束响应。这样,只有GridView中的数据会被导出到Excel文件中。
本文共计578个文字,预计阅读时间需要3分钟。
您可以使用以下代码片段来仅导出GridView中的数据到Excel,而不是整个页面:
csharpHtmlForm form=new HtmlForm();Response.Clear();Response.Buffer=true;Response.ContentType=application/vnd.ms-excel;Response.AddHeader(Content-Disposition, attachment;filename=GridViewData.xlsx);Response.Charset=UTF-8;
StringBuilder sb=new StringBuilder();sb.Append();
// 假设GridView的名称为myGridViewGridView myGridView=(GridView)Page.FindControl(myGridView);foreach (GridViewRow row in myGridView.Rows){ sb.Append(); foreach (TableCell cell in row.Cells) { sb.AppendFormat({0}, cell.Text); } sb.Append();}
sb.Append();
Response.Write(sb.ToString());Response.End();
这段代码首先创建一个新的HtmlForm,然后清除响应并设置内容类型为Excel。接着,它遍历GridView的每一行和每一列,将数据格式化为HTML表格,并将表格内容写入响应流中,最后结束响应。这样,只有GridView中的数据会被导出到Excel文件中。

