C# 在asp.net中创建Excel工作簿
我需要为fl上的用户在单击按钮时生成excel文件。我以前使用过它,它在桌面应用程序中运行良好。C# 在asp.net中创建Excel工作簿,c#,asp.net,vsto,ms-office,C#,Asp.net,Vsto,Ms Office,我需要为fl上的用户在单击按钮时生成excel文件。我以前使用过它,它在桌面应用程序中运行良好。 但是现在我想用asp.net应用程序做同样的事情。这样,我的服务器代码就无法访问客户端的excel副本。我应该采取什么方法 您可以尝试使用简单的HTML表格(包括HTML、head和body标记)。 只需使用XLS扩展名保存即可 最灵活、最有可能做您需要的事情的方法是做一些工作,但它是免费的,而且确实有效。使用工具箱查看现有文档,了解如何创建所需的功能 使用。它允许您在服务器上创建Excel电子表
但是现在我想用asp.net应用程序做同样的事情。这样,我的服务器代码就无法访问客户端的excel副本。我应该采取什么方法 您可以尝试使用简单的HTML表格(包括HTML、head和body标记)。 只需使用XLS扩展名保存即可
最灵活、最有可能做您需要的事情的方法是做一些工作,但它是免费的,而且确实有效。使用工具箱查看现有文档,了解如何创建所需的功能 使用。它允许您在服务器上创建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();
}
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();
}
}
}
不,我需要一些复杂的excel操作。netoffice可以很好地工作,但我不明白为什么它不能与asp.NET一起工作。netoffice看起来很酷。虽然我找不到如何创建工作簿并将其下载到客户端而不保存到服务器的示例?你知道一个简单的方法吗?我添加了一些代码,显示如何使用电子表格创建工作簿并将其写入客户端。是否应将EPPlus作为Dll下载并链接到我的项目参考?我想使用它…看起来很像这个解决方案返回HTML到客户端,但声明它实际上是一个Excel文件。问题是Excel发现了你的小欺骗,并向用户抛出警告对话框,解释有人试图对他们撒谎。