如何在 .net 2.0 中将数据从数据库或 DataTable 保存到 Excel 文件而没有响应

how to save data from database or DataTable To Excel File without Response in .net 2.0

我有一个用 asp.net 2.0 和 C# 开发的旧网站,我想将数据从数据库或 DataTable 保存到 Excel 文件。

我在互联网上搜索了很多,但只找到了使用 HttpResponce "Responce.Write" 的解决方案,但是如果文件很大,这个解决方案将不起作用,所以我想要一个解决方案来物理保存 excel 文件在硬盘上。

在大多数情况下,为了使用 Excel 相关库(即 Microsoft.Office.Interop 命名空间)。 可以使用 CSV 文件吗?这可能要简单得多。只需将您的 DataTable 对象加载到 FileStream 中,然后保存文件。

你有什么环境,Excel结果文件应该针对哪个版本?视情况而定,答案可能会有所不同。但或多或少是通用的 - 尝试使用 GemBox.Spreadsheet,它不需要安装 Excel,但它在免费版本中有限制。

如果我的机器上没有安装 Excel,我找到了解决方案,并决定与 public 分享

方案一(如果需要将excel文件物理保存在硬盘上)

您将需要一个 gridview 来首先将数据放入其中,而不需要任何 css 或样式,只需从数据库中以您需要的格式在 excel 文件

中获取选定的数据

<!-- GridView to bind data from DatasSet-->
<asp:GridView ID="GridView2" runat="server" Visible="False"></asp:GridView>
<!-- HyperLink to put the link of the saved file -->
<asp:HyperLink ID="HyperLink1" runat="server" Visible="False">HyperLink</asp:HyperLink>

代码隐藏

    private void ConvertDataSetToExcelFile(DataSet ds)
    {
        GridView2.DataSource = ds.Tables[0];
        GridView2.DataBind();
        string FileName = DateTime.Now.Ticks.ToString() + ".xls";
        string FilePath = Server.MapPath("~/upload/excel/");

        GridView2.Visible = true;
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
        GridView2.RenderControl(htw);
        string renderedGridView = sw.ToString();
        System.IO.File.WriteAllText(FilePath + FileName, renderedGridView);
        GridView2.Visible = false;

        HyperLink1.Visible = true;
        HyperLink1.NavigateUrl = "~/upload/excel/" + FileName;
        HyperLink1.Text = "Download File";
    }

请注意,您需要先将 GridView 设置为可见 true 才能将其呈现到文件中,如果它是可见的 false 则无需呈现任何内容,然后您可以再次将其设置为 false 因为它仅用于保存数据然后将其呈现到文件




解决方案2(如果您需要即时创建文件,则直接将其下载到客户端即可)

请注意,我在搜索中发现了这些功能,但我没有尝试,因为我需要第一个解决方案,但只想分享 public 的另一个解决方案

public static void ExportToExcel(ref GridView gv, string _filename, string cmplbl)
{

    string style = @"<style>.text{mso-number-format:\@;text-align:center;};.Nums{mso-number-format:_(* #,###.00_);};.unwrap{wrap:false}</style>";
    //string style = @"<style> .text { mso-number-format:\@; } </style> ";

    // "<style>.text{mso-number-format:\@;text-align:center;};.Nums{mso-number-format:_(* #,##0.00_);};.unwrap{wrap:false}</style>"

    string attachment = "attachment; filename=" + _filename;
    HttpContext.Current.Response.ClearContent();

    HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    // If you want the option to open the Excel file without saving then;
    // comment out the line below
    // Response.Cache.SetCacheability(HttpCacheability.NoCache);

    HttpContext.Current.Response.ContentType = "application/ms-excel";
    //Response.AddHeader("Content-Disposition", "attachment;Filename=Orders.xls");

    //Response.Write ("<meta http-equiv=""Content-Type"" content=""text/html; charset=Utf-8"">")

    StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw);
    gv.RenderControl(htw);
    StringBuilder name = new StringBuilder();
    name.Append(cmplbl);
    HttpContext.Current.Response.Write(style);
    HttpContext.Current.Response.Write(name.Append(sw.ToString()));
    //HttpContext.Current.Response.Write(sw.ToString());

    HttpContext.Current.Response.End(); 

    //HttpContext.Current.Response.WriteFile(_filename);
    //Response.ContentType = "application/vnd.ms-excel"
    //Response.AddHeader("Content-Disposition", "attachment;Filename=Orders.xls")
    //Response.Write ("<meta http-equiv=""Content-Type"" content=""text/html; charset=Utf-8"">")
    //dbGrid_Orders.RenderControl(hw)
    //Response.Write(tw.ToString())
    //Response.End()
}

private void ExportGridView(GridView gvFiles, string filePath, string fileName)
{
    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(filePath + fileName, renderedGridView);

    //Response.Clear(); 
    //Response.ContentType = "application/octect-stream";
    //Response.AppendHeader("content-disposition", "filename=" + fileName);
    //Response.TransmitFile(filePath + fileName); 
    //Response.End();

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition",
                       "attachment; filename=" + fileName + ";");
    response.TransmitFile(filePath + fileName);
    response.Flush();
    response.End();
}