Jujumancer
Jujumancer

Reputation: 125

Read Excel file without headers ASP.Net

I am trying to follow this code to read Excel files. Unfortunately, I cannot make it work, because I need to read Excel files without headers. How can I read an Excel files without headers?

public static DataTable ToDataTable(this ExcelPackage package)
    {
        ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
        DataTable table = new DataTable();


        foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
        {
            table.Columns.Add(firstRowCell.Text);
        }

        for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
        {
            var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
            var newRow = table.NewRow();
            foreach (var cell in row)
            {
                    newRow[cell.Start.Column-1] = cell.Text;
            }
            table.Rows.Add(newRow);  
        }
        return table;
    }

Upvotes: 0

Views: 1464

Answers (2)

Jujumancer
Jujumancer

Reputation: 125

I was able to make a work around with the problem. I automatically added columns. Changing to foreach to a for loop.

for (int x = 0; x <= workSheet.Dimension.End.Column; x++)
        {
            table.Columns.Add(x.ToString());
        }

Upvotes: 0

Ghasan غسان
Ghasan غسان

Reputation: 5877

You can see in the for statement that it loops starting from the second row (skipping the header), what you need is to loop from the first row (as there is no header row) like this:

var rowNumber = 1

If your data is empty at the first row, then please add how many columns you are expecting to be there in the file:

// Notice I replaced workSheet.Dimension.End.Column with 6, because I am expecting 6 columns.
foreach (var firstRowCell in workSheet.Cells[1, 1, 1, 6])
{
    table.Columns.Add(firstRowCell.Text);
}

Upvotes: 1

Related Questions