在asp.net中创建excel工作簿
我需要在点击按钮时为用户生成一个excel文件。我之前使用Netoffice,之前在桌面应用程序中工作得很好。 但现在我想用asp.net应用程序做同样的事情。这样我的服务器代码就无法访问客户端的excel副本。我应该采取什么方法?在asp.net中创建excel工作簿
使用EPPlus。它允许您在服务器上创建Excel电子表格。我已经使用它,它运作得很好。它支持高级功能。
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(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.Clear();
Response.AddHeader("content-disposition", "attachment; filename=file.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
看起来很酷。虽然我找不到如何创建工作簿并将其下载到客户端而不保存到服务器的示例?你知道一个简单的方法吗? – user194076 2012-04-07 20:39:30
我添加了一些代码,显示用电子表格创建工作簿并将其写入客户端。 – 2012-04-07 21:12:36
非常感谢! – user194076 2012-04-07 21:19:54
您可以尝试简单的HTML表格(包括html,head和body标签)。 只需使用XLS扩展名保存即可。
不,我需要一些复杂的操作脱颖而出。 netoffice会很好,但我不明白为什么它不能与asp.net – user194076 2012-04-07 20:30:53
Netoffice需要MS Office执行机器。你的服务器有吗?
您可以使用DataGrid快速创建Excel文件。它不需要Excel。
public static void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader(
"Content-Disposition",
"attachment;filename=\"" + filename + "\""
);
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
dg.Dispose();
ds.Dispose();
response.End();
}
}
}
该解决方案将** HTML **返回给客户端,但声明它实际上是一个** Excel **文件。问题在于Excel对你的小欺骗很感兴趣,并向用户抛出一个警告对话,解释有人试图对他们说谎。 – 2012-10-17 13:49:37
看起来很像http://stackoverflow.com/questions/150339/generating-an-excel-file-in-asp-net – Mathias 2012-04-08 17:16:35