我开发了一个在线商店的应用程序,其中不同的商店在线保存目录。但我必须开发一个功能,在xls文件中下载目录,因为我有数据表中的数据,我必须用动态生成的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();
但我没有得到任何东西
请帮助摆脱它。
答案 0 :(得分:2)
我使用EPPlus包,您可以通过Nuget安装。它允许您直接从数据表中将数据加载到Excel工作表中,它包括对工作表上的格式(字体,列宽等)等内容的支持。看他们的 关于在Web应用程序中使用它的文档页面here。
对于你的情况,我会建议像:
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());
}
答案 1 :(得分:0)
试试这个
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();