0

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;
    }
1

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Changed it to 1 but it gives me an error says the cannot find column 0.
Line 30: newRow[cell.Start.Column - 1] = cell.Text;
Basically the excel file's structure is the first row is empty.
0

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());
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.