Monday, January 9, 2012

Export DataGridView to MS Excel

Sometime, you want to export data from you application to MS excel file. Here is code demo.
Code simpy export excel from datagridview, with some little custom you can export something else.


   1:  using System;
   2:  using System.Windows.Forms;
   3:  using Microsoft.Office.Interop.Excel;
   4:  using Application = Microsoft.Office.Interop.Excel.Application;
   5:   
   6:  namespace CompareDatabaseTool
   7:  {
   8:      public static class Utils
   9:      {
  10:          public static void ExportToExcel(DataGridView dgvList, string fileName)
  11:          {
  12:              _Application app = new Application();
  13:              _Workbook workbook = app.Workbooks.Add(Type.Missing);
  14:   
  15:              //app.Visible = true;
  16:              _Worksheet worksheet = workbook.ActiveSheet;
  17:              worksheet.Name = "Exported";
  18:   
  19:              for (int i = 1; i <= dgvList.Columns.Count; i++)
  20:              {
  21:                  worksheet.Cells[1, i] = dgvList.Columns[i - 1].HeaderText;
  22:              }
  23:   
  24:              for (int i = 0; i < dgvList.Rows.Count; i++)
  25:              {
  26:                  for (int j = 0; j < dgvList.Columns.Count; j++)
  27:                  {
  28:                      worksheet.Cells[i + 2, j + 1] = dgvList[j, i].Value.ToString();
  29:                  }
  30:              }
  31:   
  32:              workbook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  33:                              Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing,
  34:                              Type.Missing, Type.Missing, Type.Missing);
  35:   
  36:              app.Quit();
  37:          }
  38:      }
  39:  }
Hope it useful!

No comments:

Post a Comment