How to read open excel file at C#

前端 未结 6 2095
北海茫月
北海茫月 2020-12-17 16:47

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.

FileStre         


        
相关标签:
6条回答
  • 2020-12-17 17:31

    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.

    0 讨论(0)
  • 2020-12-17 17:34

    You need to open it with FileShare.ReadWrite:

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

    See this answer.

    0 讨论(0)
  • 2020-12-17 17:36

    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)) 
    {
    
    }
    
    0 讨论(0)
  • 2020-12-17 17:37

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

    oExcel == (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
    
    0 讨论(0)
  • 2020-12-17 17:39

    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.

    0 讨论(0)
  • 2020-12-17 17:49

    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.

    0 讨论(0)
提交回复
热议问题