How to write excel file from datatable in c#

Total Post:412


 17454  View(s)
Rate this:

Hello Everyone,

Can anyone tell me how to write excel file from datatable in C#.Net. Please resolve my problem as soon as possible.

Thanks in advance!!

  1. Re: How to write excel file from datatable in c#

    Hello Pravesh Singh,
    Check this code...
    // Create sql connection string
    string conString = @"Data Source =  ServerName ; Initial Catalog = MyDatabase; User Id = XXXXXX ; Password = XXXXXX;";
    SqlConnection sqlCon = new SqlConnection(conString);
    // Fill data into MyTable
    SqlDataAdapter da = new SqlDataAdapter("select * from MyTableName", sqlCon);
    System.Data.DataTable dtMainSQLData = new System.Data.DataTable();
    DataColumnCollection dcCollection = dtMainSQLData.Columns;
    // Export Data into EXCEL Sheet

    Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
     // Write data into excel sheet cells

    for (int i = 1; i < dtMainSQLData.Rows.Count + 1; i++)
      for (int j = 1; j < dtMainSQLData.Columns.Count + 1; j++)
     if (i == 1)
        ExcelApp.Cells[i, j] = dcCollection[j - 1].ToString();
      ExcelApp.Cells[i, j] = dtMainSQLData.Rows[i - 1][j - 1].ToString();
    // save excel file
    ExcelApp.ActiveWorkbook.Saved = true;
    It might be resolve your problem.

      Modified On Jan-10-2012 08:44:04 AM
  1. Re: How to write excel file from datatable in c#


    You can use this Excel .NET component to write excel file from a datatable.
    The C# code below shows how to do this:

    DataTable dt = new DataTable();
    ExcelWorkbook Wbook = new ExcelWorkbook();

      Modified On Mar-29-2018 10:52:59 PM
  1. Re: How to write excel file from datatable in c#

    You can turn a DataTable into an Excel worksheet with some very readable code:

    XLWorkbook wb = new XLWorkbook();

    DataTable dt = GetDataTableOrWhatever();



Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.