Thursday, April 17, 2014

Export DataTable To Excel in c# windows application

 public static void ExportDTToExcel(System.Data.DataTable dt,string FileName)
      {

        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        app.Visible = false; 

        Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

        Worksheet ws = (Worksheet)wb.ActiveSheet; 
        
        // Headers.

        for (int i = 1; i < dt.Columns.Count; i++)
        {
          ws.Cells[1, i] = dt.Columns[i].ColumnName;
        } 

        // Content.

        for (int i = 0; i < dt.Rows.Count; i++)
        {

          for (int j = 1; j < dt.Columns.Count; j++)
          {

            ws.Cells[i + 2, j ] = dt.Rows[i][j].ToString();

          }

        } 

        // Lots of options here. See the documentation.

        wb.SaveAs(FileName );


        wb.Close();

        app.Quit();

      }

1 comment:

Anonymous said...

nice work done.Helped me a lot . Thanks once again

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...