C# 如何将数据写入excel文件并在asp.net中下载

C# 如何将数据写入excel文件并在asp.net中下载,c#,asp.net,excel,C#,Asp.net,Excel,我已经为网上商店开发了一个应用程序,其中不同的商店在线保存目录。但我必须开发一个功能,在xls文件中下载目录,因为我的数据在datatable中,我必须在动态生成的xls文件中写入数据并下载 为此,我尝试了休闲: DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT * FROM Products_Details_View WHERE Supp_Id = " + Session["SuppID"].ToString() +

我已经为网上商店开发了一个应用程序,其中不同的商店在线保存目录。但我必须开发一个功能,在xls文件中下载目录,因为我的数据在datatable中,我必须在动态生成的xls文件中写入数据并下载

为此,我尝试了休闲:

DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT *  FROM Products_Details_View WHERE   Supp_Id = " + Session["SuppID"].ToString() + " and Is_Available = 1"); 
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=Catalog.xls");
Response.ContentType = "application/excel";
Response.Write(ProductDetails);
Response.End();

但是我什么也没有得到

请帮我摆脱它。

我使用这个软件包,你可以通过Nuget安装。它允许您直接从datatable将数据加载到Excel工作表中,并支持工作表上的格式设置(字体、列宽等)。看他们的 有关在web应用程序中使用它的文档页面

对于你的情况,我建议如下:

DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT *  FROM Products_Details_View WHERE Supp_Id = " + Session["SuppID"].ToString() + " and Is_Available = 1"); 

using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. 
    //Print the column names on row 1
    ws.Cells["A1"].LoadFromDataTable(ProductDetails, true);

    //Write it back to the client
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;  filename=ProductDetails.xlsx");
    Response.BinaryWrite(pck.GetAsByteArray());
}
试试这个

string attachment = "attachment; filename=xxxx" + DateTime.Now + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
ProductDetails.RenderControl(htextw);

GridView dg = new GridView(); //Create an empty Gridview to bind to datatable.
dg.AutoGenerateColumns = true;
dg.DataSource = ProductDetails;
dg.DataBind();

dg.RenderControl(htw);
Response.Write(stw.ToString());
stw.Close();
Response.End();