简体   繁体   中英

C# ExcelPackage (EPPlus) DeleteRow does not change sheet dimension?

I am trying to build a data import tool that accepts an EXCEL file from the user and parses the data from the file to import data into my application.

I am running across a strange issue with DeleteRow that I cannot seem to find any information online, although it seems like someone would have come across this issue before. If this is a duplicate question, I apologize, however I could not find anything related to my issue after searching the web, except for this one which still isn't solving my problem.

So the issue:

I use the following code to attempt to "remove" any row that has blank data through ExcelPackage.

                for (int rowNum = 1; rowNum <= ws.Dimension.End.Row; rowNum++)
                {
                    var rowCells = from cell in ws.Cells
                                        where (cell.Start.Row == rowNum)
                                        select cell;
                    if (rowCells.Any(cell => cell.Value != null))
                    {
                        nonEmptyRowsInFile += 1;
                        continue;
                    }
                    else ws.DeleteRow(rowNum);
                    //Update: ws.DeleteRow(rowNum, 1, true) also does not affect dimension
                }

Stepping through that code, I can see that the DeleteRow is indeed getting called for the proper row numbers, but the issue is when I go to set the "total rows in file" count on the returned result object:

parseResult.RowsFoundInFile = (ws.Dimension.End.Row);

ws.Dimension.End.Row will still return the original row count even after the calls to DeleteRow.

My question is...do I have to "save" the worksheet or call something in order for the worksheet to realize that those rows have been removed? What is the point of calling "DeleteRow" if the row still "exists"? Any insight on this would be greatly appreciated...

Thanks

I think I figured out the problem. This is yet again another closure issue in C#. The problem is that the reference to "ws" is still the same reference from before the DeleteRow call.

In order to get the "updated" dimension, you have to redeclare the worksheet, for example:

 ws = excelPackage.Workbook.Worksheets.First();

Once you get a new reference to the worksheet, it will have the updated dimensions, including any removed/added rows/columns.

Hopefully this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM