简体   繁体   中英

Programmatically getting the total no. of rows having data in excel sheet using C#

Mine is C# console application. I am trying to get the count of rows which are having data of an excel sheet programmatically, using C# with the reference of EPPlus Library. I want to read all the records of an excel spreadsheet using for loop. So I need to specify the upper limit of that loop.

code i used:-

FileInfo existingFile = new FileInfo(FilePath);
        using (ExcelPackage package = new ExcelPackage(existingFile))
        {
            // get the second worksheet in the workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets[2];

// output the data in column 2 StringBuilder sb = new StringBuilder(); for (int row = 2; row < 7; row++) { sb.Append("<tr>"); for (int col = 2; col < 11; col++) { if (col == 7) sb.Append("<td valign='top' border='1'><a href='https://na7.salesforce.com/'" + worksheet.Cells[row, col].Value + ">" + "https://na7.salesforce.com/" + worksheet.Cells[row, col].Value + "</td>"); else sb.Append("<td valign='top' border='1'>" + worksheet.Cells[row, col].Value + "</td>"); } sb.Append("</tr>"); } }

Now am statically mentioning that the code must retrieve 7 rows [for (int row = 2; row < 7; row++)]. Here the 7 must be calculated dynamically (during the run-time).

Kindly popup your points here to work it out. Thanks in advance.

You could do something like this:

var rowCount =  worksheet .Dimension.End.Row

This returns the number of the last row with data. Than you can simply loop until this number.

Obviously, this will not work if you have garbage like comments at the end of yor sheet, than there will more rows.

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