简体   繁体   English

使用C#中的interop以独占模式打开Excel文件

[英]Open an excel file in exclusive mode using interop in C#

In my application I want to be able to open an excel file that already exists, and add information to this file. 在我的应用程序中,我希望能够打开已存在的excel文件,并向此文件添加信息。 I use the Microsoft Interop libraries. 我使用Microsoft Interop库。 I have noticed that if you create a new spreadsheet using Add and then Saveas you can set the file to be in exclusive mode until you close the excel application. 我注意到,如果使用“添加”然后“保存”创建新电子表格,则可以将文件设置为独占模式,直到关闭Excel应用程序。

However I haven't found a way to do the same when Opening an existing file. 但是,在打开现有文件时,我还没有找到相同的方法。 The reason I want to do that is because, if I open the excel file while my application is open, then I get an exception. 我想这样做的原因是,如果我在应用程序打开时打开excel文件,那么我会得到一个例外。 I presume that when I am opening the excel file using excel, it is automatically opened in exclusive mode. 我假设当我使用excel打开excel文件时,它会以独占模式自动打开。

I though of opening the file and then using saveas, but it didn't work. 我虽然打开文件然后使用saveas,但它没有用。

private object missing=Type.Missing;
workbook = workbooks.Open(excelfilename,missing, false, missing, missing, missing,missing,missing,missing,missing,false, missing,missing, missing, missing);
workbook.SaveAs((String)excelfilename, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, missing, missing, missing, missing); 

I am getting the exception later in the code: 我稍后在代码中得到异常:

Excel.Range testrange = sheet.get_Range(rangetext);

The exception I am getting is a COMException, "Exception from HRESULT: 0x800401A8". 我得到的异常是一个COMException,“来自HRESULT的异常:0x800401A8”。

您可以转到本文以获取有关如何使用Microsoft互操作库打开Excel文件/添加新工作表/获取范围和设置属性的完整示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM