使用ASP.NET网站生成Excel文档
我有一个ASP.NET应用程序,可以帮助用户创建包含某些数据的Gridview。生成此表后,我希望用户按下按钮,并能够将该表保存为Excel文档。我知道有两种不同的方法:使用ASP.NET网站生成Excel文档,asp.net,excel,office-automation,Asp.net,Excel,Office Automation,我有一个ASP.NET应用程序,可以帮助用户创建包含某些数据的Gridview。生成此表后,我希望用户按下按钮,并能够将该表保存为Excel文档。我知道有两种不同的方法: 使用内容类型为“application/vnd.ms excel”的HtmlTextWriter将文件作为HttpResponse发送。我使用GridView1.RenderControl(htmlTextWriter)渲染gridview。这几乎可以工作,但excel文件在打开时总是显示警告,因为内容与扩展名不匹配。我尝试过
这看起来是一个有用的工具,但我正在为我的公司纠正这个web应用程序,我认为GNU许可证不会奏效。从这里以及我在谷歌搜索的其他帖子中找不到答案,我得到的印象是,没有第三方工具就没有好办法!?真的是这样吗?ePlus是最好的方法,如果你想要一个产品,我可以推荐soft artisans excel/office writer,但是如果没有第三方,它相当昂贵,是的,epplus是用c#和.net编写的,所以看一下源代码,自己做同样的事情……我看了epplus页面,但在页面上的所有源代码中都找不到我需要的代码。我现在正在使用Excel类。它可以工作,但我还是不太高兴,因为微软的通知,因为我不是一个办公室自动化工具的球迷一般。仍然感谢您的帮助。您不应该在服务器上使用excel自动化
using (ExcelPackage pck = new ExcelPackage())
{
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(tbl, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//Example how to Format Column 1 as numeric
using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}