Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Epplus Csharp | How to manipulate already opened(in use) Excel File

Tags:

epplus

Epplus Csharp | How to manipulate already opened(in use) Excel File. it works only when Excel file is closed. I can do like closing before code execution and reopen again, but do not think it's a way to go as my file contains more than 50000 rows (file size is big). Please advise, how to figure it out.

Thanks in advance

like image 411
user610961 Avatar asked Nov 14 '13 06:11

user610961


2 Answers

Rather than using a FileInfo to open the ExcelPackage workbook, use a stream:

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
ExcelPackage pkg = new ExcelPackage(fs);
  • path is the path to the file that you would otherwise use for FileInfo
  • FileMode says you want to open it
  • FileAccess says you want to read it
  • FileShare says that other programs can read/write.

With the workbook specified by path open in excel, you will be able to read lines from the file, but will get an exception if you try to call ExcelPackage.Save().

like image 198
Ron Chibnik Avatar answered Nov 18 '22 03:11

Ron Chibnik


It is only possible, if the file is opened for reading by a third-party, but not for writing.

If the third-party opened the file for writing, your attempt to open the same file even just for reading will result in System.IO.IOException. In fact, it's all about FileStream and not specific to EpPlus and ExcelPackage. Example in terms of .NET:

var fileStream1 = new FileStream(@"File.ext", FileMode.Open, FileAccess.Read);
var fileStream2 = new FileStream(@"File.ext", FileMode.Open, FileAccess.Read);

will work just fine. But the second line of the following fragment:

var fileStream1 = new FileStream(@"File.ext", FileMode.Open, FileAccess.Write);
var fileStream2 = new FileStream(@"File.ext", FileMode.Open, FileAccess.Read);

will result in a System.IO.IOException.

like image 25
Deilan Avatar answered Nov 18 '22 04:11

Deilan