Visual Studio 2012:如何打开与我的项目关联的 excel 文件?

Visual Studio 2012: How do I open an excel file that is associated with my project?

所以我正在开发一个项目,该项目使用 excel 文件向用户控件添加“描述”。截至目前,我的代码使用绝对路径打开 excel 文件,像这样

Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\absolute path\filename.xlsx", Type.Missing, Type.Missing
                                                                 , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                                                 , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                                                 , Type.Missing, Type.Missing);

效果很好。

然后我尝试重命名该文件(只是为了确保 C:\ 文件没有因为某些奇怪的原因而被打开)并将其添加到我的项目中,这样我就不必依赖于能够访问特定驱动器(即文件可以打开,因为它与项目相关联)。然后我尝试了以下代码:

Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"newfileName.xlsx", Type.Missing, Type.Missing
                                                                 , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                                                 , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                                                 , Type.Missing, Type.Missing);

这给了我这个:

"Additional information: 'newfileName.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct."

我想知道将 excel 文件添加到项目并使用相对路径名打开它的正确方法是什么?

第二个示例试图在工作目录中打开此文件。因此,如果您想在构建时复制此文件,只需将此文件 "Copy to Output Directory" 属性 更改为 "true"

如果您想将文件与您的项目相关联,那么您需要资源。在这里您可以看到如何将资源添加到您的项目:

How to create and use resources in .NET

资源是流。它们存储在内存中。所以我会推荐你​​使用一个 class ,它需要 Stream。不是文件的路径。

因为Workbooks.Open 从文件路径创建流。最好寻找直接采用流的重载或替代方法 class。

var doc = SpreadSheetDocument.Open(Properties.Resources.YourFile , isEditable);

isEditable 是布尔值。您可以使用 truefalse。如果你设置为 false 它将是只读的。

我建议你看一下这个主题:

How to: Open a spreadsheet document from a stream (Open XML SDK)

如果您想使用当前的任何方式 class。您必须将 Stream 临时保存到磁盘中并从中获取路径。它可以工作,但是有很多额外的工作要做,因为您可以直接使用 Stream。

 string path = Path.GetTempPath(); // Creates a  Temp path for temporary file.
 Properties.Resources.Yourfile.Save(path); // Save the file into path.
 // Now you can use path to load file with xlApp.Workbooks.Open again!
 Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path,...);