2

I'm importing an Excel file by C# through below code. But when I check at database I see one null row is added.

Can you help me to change this code to delete this null row?

public static class ExcelTools
{
    static DataSet result = new DataSet();
    public static DataTable ExcelToDataTable(string path)
    {
        var pck = new OfficeOpenXml.ExcelPackage();
        pck.Load(File.OpenRead(path));
        var ws = pck.Workbook.Worksheets.First();
        DataTable tbl = new DataTable();
        bool hasHeader = true;
        foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
        {
            tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
        }
        var startRow = hasHeader ? 2 : 1;
        for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
        {
            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
            var row = tbl.NewRow();
            foreach (var cell in wsRow)
            {
                row[cell.Start.Column - 1] = cell.Text;
            }
            tbl.Rows.Add(row);
        }
        pck.Dispose();
        tbl.TableName = System.IO.Path.GetFileNameWithoutExtension(path);
        return tbl;
    }
}

enter image description here

Shafieh F
  • 21
  • 2

1 Answers1

1

You might have been fooled by the last NULL row:

enter image description here

that allows you to add a row manually. Which means that it isn't in your Database. To be sure, you can count null rows:

select sum(case when [COL] is null then 1 else 0 end) count_nulls
from [TABLE]
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142