Worksheet position out of range. Connection Closed. When using EPPLUS

。_饼干妹妹 提交于 2020-03-18 11:08:47

问题


I am trying to open an XLSX file as a template (I have even used a blank XLSX file), using EPPLUS 4.0.3.

If I do not open the template file (blank or the real one) and just create a new workbook and create a sheet, it works fine. OR if I open the template file, and create a NEW worksheet, then it works fine. It is only when I try to access the FIRST sheet in the template that I get the error: Worksheet position out of range.

Accessing the first worksheet like this: workBook.Worksheets.First() DOES NOT WORK.

First is no longer a definition.

So I tried accessing the first worksheet by name and by this method workBook.Worksheets[1] using both 0 and 1 to try to get the first sheet.

MY CODE:

    var existingTemplate = new FileInfo(_ExcelTemplateFilePath);
    using (ExcelPackage p = new ExcelPackage(existingTemplate)) {
    // Get the work book in the file
    ExcelWorkbook workBook = p.Workbook;
    ExcelWorksheet ws = workBook.Worksheets[1];
    // MY OTHER EXCEL CELL CODE HERE    
}}

Does anyone know how to access the first sheet of and Excel file?


回答1:


I was able to get around this issue by referring to the worksheet by name, rather than index.

var oSheet = package.Workbook.Worksheets["My Worksheet Name"];



回答2:


to get the first sheet just use the below code

    var xlWorkbook = new ExcelPackage(new FileInfo(@"C:\ESD\EXCELDATAREADTEST.xlsx"));

ExcelWorksheet workSheet = xlWorkbook.Workbook.Worksheets[1];

just make sure you're pointing to the correct location for your workbook




回答3:


I just had this same problem and the trouble is that EPPlus chokes on spreadsheets with named ranges.

Here's what I did (using LibreOffice Calc) to enable reading the spreadsheet:

  1. Create a copy of the spreadsheet
  2. Open in LibreOffice
  3. List item
  4. Click the drodpwon on the upper left corner for defining ranges. Typically reads "A1"
  5. Select "Manage Names"
  6. Highlight the entire list
  7. Click "Delete"

Once I completed those steps, I saved/closed the spreadsheet and was able to open it with EPPlus.




回答4:


I used

var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();

This is because the sheet might not have a known name and now you are interest in the first sheet



来源:https://stackoverflow.com/questions/29775107/worksheet-position-out-of-range-connection-closed-when-using-epplus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!