如何在C#中读取打开的Excel文件

发布于 2024-10-17 10:52:15 字数 360 浏览 3 评论 0原文

我想用 C# 读取已经打开的 Excel 文件。我正在使用此方法,但当文件在 Microsoft Excel 中打开时,它无法读取 Excel 文件。

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read);

它给出了IOException:该进程无法访问文件“myfile.xlsx”,因为它正在被另一个进程使用。

我希望您明白我的意思。我想保持 Excel 文件打开,当文件在 Microsoft Excel 中打开时,我想从 C# 读取它。我正在使用 C# net Framework 4.0

I want to read already open excel file with C#. I am using this method but it can't read the excel file while the file is open in Microsoft excel.

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read);

It gives IOException: The process cannot access the file 'myfile.xlsx' because it is being used by another process.

I hope you understands what I mean. I want to keep excel file open and while file is open at Microsoft excel i want to read it from C#. I am using C# net framework 4.0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

乖乖哒 2024-10-24 10:52:16

我认为您仍然可以在 Excel 打开文件时复制该文件,因此您可以复制该文件,然后将其打开。只要确保在完成副本后自行清理即可。

I think you can still copy the file while excel has it open, so you could make a copy of the file and then open that. Just make sure you clean up after yourself when you are done with the copy.

倾其所爱 2024-10-24 10:52:16

您可以使用 Interop 库来使用已打开的 Excel 实例。

oExcel == (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")

You could use the Interop library to use the already opened instance of Excel.

oExcel == (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
半城柳色半声笛 2024-10-24 10:52:16

您可以尝试使用第四个参数 - fileShare 的 File.Open。

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read, FileShare.Read);

您可能还需要指定写访问权限。

You can try the File.Open with a fourth parameter - fileShare.

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read, FileShare.Read);

You may need to specify write access also.

我家小可爱 2024-10-24 10:52:16

为了确保正确打开和关闭文件,请查看使用 c# using 语句

using (FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read)) 
{

}

To ensure that correct opening and closing of the file please look at using the c# using statements

using (FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read)) 
{

}
紙鸢 2024-10-24 10:52:16

要同时多次打开同一个文件,需要以共享模式打开。

希望这可以帮助其他人。

To open the same file more than once at the same time, it needs to be opened in shared mode.

Hope this may help others.

很快妥协 2024-10-24 10:52:15

您需要使用 FileShare.ReadWrite 打开它:

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

请参阅此答案

You need to open it with FileShare.ReadWrite:

FileStream stream = File.Open("myfile.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

See this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文