0

I'm using the following code to extract data from sheets within a workbook using EPPlus. The code works fine, except when the workbook is open in Excel. The code returns no data when the Excel file is kept open by the user. How can I get over this issue?

var fileInfo = new FileInfo(@file);

using (var package = new ExcelPackage(fileInfo))
                {
                    label_snum.Text = package.Workbook.Worksheets.Count.ToString();
                    // Itterate through workbook sheets
                    foreach (var sheet in package.Workbook.Worksheets)
                    {
                        label_csheet.Text = sheet.Name;
                        // Itterate through each column until final column
                        for (int i = 1; i <= sheet.Dimension.End.Column; i++)
                        {
                            for (int j = 1; j <= sheet.Dimension.End.Row; j++)
                            {
                                if (sheet.Cells[j, i].Text.Length != 0)
                                {

                                }
                             }    
                    }  
                }                  
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
techno
  • 6,100
  • 16
  • 86
  • 192

2 Answers2

0

Have you thought about trying to connect to Excel file using a connection string instead of trying to access the opened file?

ConnectionString: Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\PathtoYourExcelFile.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";

Then you can use Linq/SQL queries to pull in the data.

"SELECT * FROM [sheet1$]" 
0

Refer to the answer here that I originally linked as a comment.

new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

To further explain, a file cannot be read when passing a FileInfo to ExcelPackage if it is being used by another process.

Prior to v4.5.1 of EPPlus, ExcelPackage uses System.IO.File.ReadAllBytes to load a file. ReadAllBytes uses the FileShare.Read setting which is incorrect because Excel opens files using the FileShare.ReadWrite setting.

When you open an already opened file, you also need to use the same FileShare setting. So by using a FileStream, you can supply the correct FileShare.

From v4.5.1, ExcelPackage now does this for you now when passing a FileInfo.

singularhum
  • 5,072
  • 2
  • 24
  • 32