0

I am trying to transform a datatbale to Excel using this funtion

    internal static bool DataTableToExcel(System.Data.DataTable dataTable, string path)
    {
        _Excel.Application objXL = objXL = new _Excel.Application();
        _Excel.Workbook objWB = null;
        _Excel.Worksheet ExcelWorkSheet = null;
        try
        {
            objWB = objXL.Workbooks.Add(_Excel.XlWBATemplate.xlWBATWorksheet);
            ExcelWorkSheet = objWB.Worksheets[1];

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    ExcelWorkSheet.Cells[i + 1, j + 1] = dataTable.Rows[i][j].ToString();
                }
            }

            objWB.SaveAs(path);
            objWB.Close();
            objXL.Quit();
            return true;
        }
        catch(Exception ex)
        {
            objWB.Close();
            objXL.Quit();
            return false;
        }
    }

But the final result is missing the header cells in the document: I am only obtaining the date but i need to add the header cells in the excell document too.

1 Answers1

0

In this case I believe you are missing adding the columns names before start the loop in your rows. Try something like this for sheet's first row:

ExcelWorkSheet.Cells[0,0] = datatable.Columns["columnName"].ColumnName
Dharman
  • 30,962
  • 25
  • 85
  • 135