C#: Getting the number of rows/columns with ExcelPackage

后端 未结 9 803
执念已碎
执念已碎 2021-02-03 18:59

I need to read and write data from an Excel spreadsheet. Is there a method to finding out how many rows/columns a certain worksheet has using ExcelPackage? I have the following

9条回答
  •  感动是毒
    2021-02-03 19:26

    I was using sheet.UsedRange on its own but noticed that some cells at the end of the range were blank but still included in the range.

    This works, however for efficiency you might be better staring from the last row in the range and counting back to see where your data ends (as opposed to this snippet which starts from the first row!)

            int count = 0;
            E.Range excelRange = sheet.UsedRange;
            object[,] valueArray = (object[,])excelRange.get_Value(E.XlRangeValueDataType.xlRangeValueDefault);
            if (valueArray.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < valueArray.GetUpperBound(0) + 2; i++)
                {
                    if (valueArray[i + 2, 1] == null)
                        break;
                    else
                        count++;
                }
            }
    

提交回复
热议问题