Programmatically getting the last filled excel row using C#

前端 未结 10 943
执念已碎
执念已碎 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:48

    As previously discussed, the techniques above (xlCellTypeLastCell etc.) do not always provide expected results. Although it's not difficult to iterate down through a column checking for values, sometimes you may find that there are empty cells or rows with data that you want to consider in subsequent rows. When using Excel directly, a good way of finding the last row is to press CTRL + Down Arrow a couple of times (you'll end up at row 1048576 for an XLSX worksheet) and then press CTRL + Up Arrow which will select the last populated cell. If you do this within Excel while recording a Macro you'll get the code to replicate this, and then it's just a case of tweaking it for C# using the Microsoft.Office.Interop.Excel libraries. For example:

        private int GetLastRow()
        {
            Excel.Application ExcelApp;
            ExcelApp = new Excel.Application();
    
            ExcelApp.Selection.End(Excel.XlDirection.xlDown).Select();
            ExcelApp.Selection.End(Excel.XlDirection.xlDown).Select();
            ExcelApp.Selection.End(Excel.XlDirection.xlDown).Select();
    
            ExcelApp.Selection.End(Excel.XlDirection.xlUp).Select();
    
            return ExcelApp.ActiveCell.Row;
        }
    

    It may not be the most elegant solution (I guess instead you could navigate to the final row within the spreadsheet first directly before using XlUp) but it seems to be more reliable.

提交回复
热议问题