I am having an excel file with 4 sheets. However, it is behaving incorrectly when I am reading the first sheet in my C# (.NET Core 3.1) code. The sheet has around 350-450 entries, sometimes it reads only 4 empty rows and at times the 450 rows but still 4 extra empty rows. Then I deleted a few empty rows from the end so it starts reading correctly.
This is the code I am using –
public List<Dictionary<string, string>> ReadSheet(ExcelWorksheet worksheet)
{
try
{
_logger.LogInformation("No. of rows (including header) = " + worksheet.Rows.Count());
var headers = worksheet.Cells["A1:ZZ1"].Select(c => c.Text).ToList();
_logger.LogInformation("No. of headers > " + headers.Count);
List<Dictionary<string, string>> sheetData = new List<Dictionary<string, string>>();
int count=worksheet.Rows.Count();
for (int row = 2; row <= worksheet.Rows.Count(); row++)
{
Dictionary<string, string> rowData = new Dictionary<string, string>();
for (int col = 1; col <= headers.Count; col++)
{
rowData[headers[col - 1]] = worksheet.Cells[row, col].Text;
}
sheetData.Add(rowData);
}
_logger.LogInformation("Number of rows stored:" + sheetData.Count);
return sheetData;
}
catch (Exception ex)
{
_logger.LogError("Exception:" + ex);
throw ex;
}
}
I am using the same code to read all other sheets and they have correct row count.
This excel I am using is prepared using a java code and has no extra rows added to it. I cannot manually keep deleting extra empty rows from the end.
Please advice. Thanks in advance!