Skip to main content
 首页 » 编程设计

c#之在 ASP.NET 中保存 Excel 文档

2024年02月23日16over140

问题:

我在 ASP.NET 应用程序中使用 Microsoft.Office.Interop.Excel 库,并且在工作簿中填充了工作表。我希望提示用户将文档保存到他们的机器上,但我找不到执行此操作的方法(myWorkbook.SaveAs(...) 不起作用)。

问题:

如何将工作簿保存到用户的机器上?我以前使用过 Response.Write(...) 来提示用户保存基于文本的文件 (CSV),但我不知道如何为 .xls 文件执行此操作。

奖励:

如果使用 Microsoft.Office.Interop.Excel 库无法做到这一点,我可以使用免费的(Lesser GPL-ish)库吗?

我假设微软会为此提供一个工具,但我们都知道假设...

请您参考如下方法:

正如@Jason Meckley 所说,为了使用互操作在服务器上创建 Excel 文件,您需要在机器上安装 Office。解决方法是使用 Open XML:

来自MSDN page :

Open XML SDK 2.0 for Microsoft Office

This SDK is a superset of the Open XML SDK 1.0. In addition to the functionality provided by the Open XML SDK 1.0, it leverages.NET Language-Integrated Query (LINQ) and provides classes to construct and query the contents of parts within a package. You can use functional construction for composing documents, and LINQ queries for extracting information from documents.

这里有一些我认为有用的“入门”教程:

Formatted Excel using SDK 2.0 and .NET

OpenXML SDK 2.0: Export a DataTable to Excel