Skip to content

Commit

Permalink
Start reading data from the row where there is any data
Browse files Browse the repository at this point in the history
  • Loading branch information
DWDBE committed Apr 8, 2024
1 parent a52f1d5 commit 02b46dc
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/ExcelReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,18 @@ private void LoadExcelFile()
var ds = new DataSet();
foreach (var worksheet in package.Workbook.Worksheets)
{
var firstRowNumberWithData = GetFirstRowNumberWithData(worksheet);
if (firstRowNumberWithData <= 0)
continue;

var emptyRows = new List<DataRow>();
var dataTable = new DataTable(worksheet.Name);
var hasHeader = true;
var firstRow = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column];
var dataTable = new DataTable(worksheet.Name);
var firstRow = worksheet.Cells[firstRowNumberWithData, 1, firstRowNumberWithData, worksheet.Dimension.End.Column];
for (var colNum = 1; colNum <= worksheet.Dimension.End.Column; colNum++)
{
var firstRowCell = firstRow[1, colNum];
var firstRowCell = firstRow[firstRowNumberWithData, colNum];
DataColumn column;
var header = hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column);
var header = firstRowCell.Text;
if (!dataTable.Columns.Contains(header) && !string.IsNullOrWhiteSpace(header))
{
column = dataTable.Columns.Add(header);
Expand All @@ -63,9 +66,8 @@ private void LoadExcelFile()
column.Caption = firstRowCell.Comment.Text;
}
}

var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++)

for (var rowNum = firstRowNumberWithData + 1; rowNum <= worksheet.Dimension.End.Row; rowNum++)
{
var hasValue = false;
var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column];
Expand All @@ -92,6 +94,21 @@ private void LoadExcelFile()
ExcelSet = ds;
}

private static int GetFirstRowNumberWithData(ExcelWorksheet worksheet)
{
for (var rowNum = 1; rowNum <= worksheet.Dimension?.End?.Row; rowNum++)
{
var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column];
for (var colNum = 1; colNum <= worksheet.Dimension.End.Column; colNum++)
{
string cellText = wsRow[rowNum, colNum].Text;
if (!string.IsNullOrWhiteSpace(cellText))
return rowNum;
}
}
return -1;
}

public void Dispose()
{
ExcelSet.Clear();
Expand Down

0 comments on commit 02b46dc

Please sign in to comment.