c# - 将 GridView 导出到 excel 并将 excel 文件保存到文件夹

标签 c# asp.net

我想保存导出 GridView 数据的excel文件。我已经编写了将 gridview 数据导出到 excel 的代码,但我不知道如何保存导出的文件。

以下是我将 gridview 导出到 excel 的代码:

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvFiles.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

最佳答案

你可以这样做:

private void ExportGridView()
{
    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

    // Render grid view control.
    gvFiles.RenderControl(htw);

    // Write the rendered content to a file.
    string renderedGridView = sw.ToString();
    System.IO.File.WriteAllText(@"C:\Path\On\Server\ExportedFile.xlsx", renderedGridView);
}

关于c# - 将 GridView 导出到 excel 并将 excel 文件保存到文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10411520/

相关文章:

c# - 从文件上传保存图像

asp.net - tinymce 在回发时获取 HTML 代码

c# - 在 WPF 中绘制基元非常慢。如何提高?

c# - Linq 在 .Substring() 上抛出异常

c# - 带有验证器的 FileUpload 的附加 onchange 事件

asp.net - 如何将 MVC 4 中的值四舍五入到小数点后两位。

c# - 如何在成功登录后将登录超链接更改为注销

c# - AspNetCompiler - 尝试加载格式不正确的程序

c# - 从IList <int>项中删除IList <int>项

c# - 最佳重载方法匹配...有一些无效参数 [byref/byval]