简体   繁体   English

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

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

I have an old website developed in asp.net 2.0 and C#, I want to save data from database or DataTable To Excel File. 我有一个使用asp.net 2.0和C#开发的旧网站,我想将数据库或DataTable中的数据保存到Excel文件中。

I searched a lot in the internet but ONLY found solutions using the HttpResponce "Responce.Write" but this solution will not work if the file is big so I want a solution to save the excel file physically on the hard drive. 我在互联网上进行了很多搜索,但只找到了使用HttpResponce“ Responce.Write”的解决方案,但是如果文件很大,此解决方案将无法正常工作,因此我希望有一种解决方案将excel文件物理保存在硬盘上。

In most cases you would even need to have MS Excel installed in the machine where you want to run your application, in order to use Excel related libraries (ie Microsoft.Office.Interop namespace). 在大多数情况下,您甚至需要在要运行应用程序的计算机上安装MS Excel,以便使用与Excel相关的库(即Microsoft.Office.Interop命名空间)。 Could you use CSV files? 您可以使用CSV文件吗? This could be much simpler. 这可能要简单得多。 Just load your DataTable object into a FileStream then save the file. 只需将DataTable对象加载到FileStream中,然后保存文件即可。

What environment do you have there, which version of Excel the result file should target to? 您在那里有什么环境,结果文件应定位到哪个版本的Excel? Depending on that, the answer can be different. 因此,答案可能会有所不同。 But more or less generic one - try to use GemBox.Spreadsheet , which doesn't require Excel to be installed but it has limitations in the free version. 但是或多或少是通用的-尝试使用GemBox.Spreadsheet ,它不需要安装Excel,但在免费版本中有其局限性。

i found the solution if i have no Excel installed on the machine and decided to share it with public 如果计算机上未安装Excel,我找到了解决方案,并决定与公众共享

Solution 1 (if you need to save the excel file physically on the hard disk) 解决方案1 (如果您需要将Excel文件实际保存在硬盘上)

you will need a gridview to put the data in it first without any css or styles just get the selected data from database with the format you need on excel file 您将需要一个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> 

code behind 背后的代码

    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";
    }

Just Note you need to make the GridView visible true first to render it to file if it is visible false then nothing to render then you can make it false again as it is used only to hold data then render it to file 只需注意,您需要先使GridView可见为true,然后才能将其渲染到文件(如果可见)为false,然后不进行渲染,则可以再次使其为false,因为它仅用于保存数据然后将其渲染到文件




Solution 2 (if you need to just create the file on the fly then just download it to client directly) 解决方案2 (如果您只需要即时创建文件,然后直接将其下载到客户端)

Just note that i found these functions on my search but i don't try then as i need the first solution but only wanted to share the other solution for public as well 只是请注意,我在搜索中发现了这些功能,但是我没有尝试,因为我需要第一个解决方案,但只想与公众共享其他解决方案

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从响应中将数据保存(下载)为 excel 文件? - How To save(download ) data as excel file from response? 将DataTable数据保存在Excel文件asp.Net中 - Save DataTable data in Excel file asp.Net 从数据库中提取数据并使用 ASP.NET Core MVC 将其保存为 Excel 文件 - Extract data from the database and save it as an Excel file using ASP.NET Core MVC 如何将DataTable保存为Excel文件(不是csv),然后将其打开? - How to save DataTable as an Excel file (not csv) and then open it? 将DataTable作为文件保存到数据库 - Save DataTable to database as a file 如何将已下载的Excel文件数据从数据表保存到ASP.NET中的应用程序文件夹中 - How to save downloaded Excel file data from Data table into application folder in ASP.NET 将数据从DataTable导出到Excel文件 - Export data from DataTable to Excel file Excel文件数据到数据表 - excel file data into datatable 如何从URL中获取数据并将其保存到C#.NET中的二进制文件中,而不会出现编码问题? - How to GET data from an URL and save it into a file in binary in C#.NET without the encoding mess? 如何保存从Kinect 2.0收集的主体数据并将其保存在JSON文件中? - How can i save the Body data collected from Kinect 2.0 and save it in a JSON file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM