Programmatically getting the last filled excel row using C#

前端 未结 10 918
执念已碎
执念已碎 2020-11-27 16:52

I am trying to get the last row of an excel sheet programatically using the Microsoft.interop.Excel Library and C#. I want to do that, because I am charged with looping thr

10条回答
  •  自闭症患者
    2020-11-27 17:51

    This issue is even worse when there are possibly empty cells. But you have to read a row even if only one value is filled. It can take a while when there are a lot of unfilled cells but if the input is close to correct it is rather fast.

    My solution ignores completely empty rows and returns the longest column's row count:

    private static int GetLastRow(Worksheet worksheet)
        {
            int lastUsedRow = 1;
            Range range = worksheet.UsedRange;
            for (int i = 1; i < range.Columns.Count; i++)
            {
                int lastRow = range.Rows.Count;
                for (int j = range.Rows.Count; j > 0; j--)
                {
                    if (lastUsedRow < lastRow)
                    {
                        lastRow = j;
                        if (!String.IsNullOrWhiteSpace(Convert.ToString((worksheet.Cells[j, i] as Range).Value)))
                        {
                            if (lastUsedRow < lastRow)
                                lastUsedRow = lastRow;
                            if (lastUsedRow == range.Rows.Count)
                                return lastUsedRow - 1;
                            break;
                        }
                    }
                    else
                        break;
                }
            }
            return lastUsedRow;
        }
    

提交回复
热议问题