C# .NET - Export data from Datagridview to Excel sheet

Asked By devender on 03-Mar-12 10:13 AM
I have created a pay bill windows application in C#.... Now what I have to do to export the COLUMNS from datagridview to EXCEL SHEET

plz help me....
Web Star replied to devender on 03-Mar-12 10:29 AM
Use this method to export in excel in c#.net window application using Office PIA
private void Export2Excel(DataGridView datagridview, bool captions)
{
object objApp_Late;
object objBook_Late;
object objBooks_Late;
object objSheets_Late;
object objSheet_Late;
object objRange_Late;
object[] Parameters;
string[] headers = new string[datagridview.ColumnCount-1];
string[] columns = new string[datagridview.ColumnCount-1];

int i = 0;
int c = 0;
for (c = 0; c < datagridview.ColumnCount - 1; c++)
{
headers[c] = datagridview.Rows[0].Cells[c].OwningColumn.Name.ToString();
i = c + 65;
columns[c] = Convert.ToString((char)i);
}

try
{
// Get the class type and instantiate Excel.
Type objClassType;
objClassType = Type.GetTypeFromProgID("Excel.Application");
objApp_Late = Activator.CreateInstance(objClassType);
//Get the workbooks collection.
objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks",
BindingFlags.GetProperty, null, objApp_Late, null);
//Add a new workbook.
objBook_Late = objBooks_Late.GetType().InvokeMember("Add",
BindingFlags.InvokeMethod, null, objBooks_Late, null);
//Get the worksheets collection.
objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets",
BindingFlags.GetProperty, null, objBook_Late, null);
//Get the first worksheet.
Parameters = new Object[1];
Parameters[0] = 1;
objSheet_Late = objSheets_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objSheets_Late, Parameters);

if (captions)
{
// Create the headers in the first row of the sheet
for (c = 0; c < datagridview.ColumnCount - 1; c++)
{
//Get a range object that contains cell.
Parameters = new Object[2];
Parameters[0] = columns[c] + "1";
Parameters[1] = Missing.Value;
objRange_Late = objSheet_Late.GetType().InvokeMember("Range",
BindingFlags.GetProperty, null, objSheet_Late, Parameters);
//Write Headers in cell.
Parameters = new Object[1];
Parameters[0] = headers[c];
objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty,
null, objRange_Late, Parameters);
}
}

// Now add the data from the grid to the sheet starting in row 2
for (i = 0; i < datagridview.RowCount; i++)
{
for (c = 0; c < datagridview.ColumnCount - 1; c++)
{
//Get a range object that contains cell.
Parameters = new Object[2];
Parameters[0] = columns[c] + Convert.ToString(i+2);
Parameters[1] = Missing.Value;
objRange_Late = objSheet_Late.GetType().InvokeMember("Range",
BindingFlags.GetProperty, null, objSheet_Late, Parameters);
//Write Headers in cell.
Parameters = new Object[1];
Parameters[0] = datagridview.Rows[i].Cells[headers[c]].Value.ToString();
objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty,
null, objRange_Late, Parameters);
}
}

//Return control of Excel to the user.
Parameters = new Object[1];
Parameters[0] = true;
objApp_Late.GetType().InvokeMember("Visible", BindingFlags.SetProperty,
null, objApp_Late, Parameters);
objApp_Late.GetType().InvokeMember("UserControl", BindingFlags.SetProperty,
null, objApp_Late, Parameters);
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);

MessageBox.Show(errorMessage, "Error");
}
}
dipa ahuja replied to devender on 03-Mar-12 11:19 AM
Add the reference in your project. Right click on the project -  > add reference
 
Now from the COM tab add two references
1.    Microsoft Office 12.0 Object Library
2.    Microsoft Excel 12.0 Object Library
 
  using Excel = Microsoft.Office.Interop.Excel;
 private void btnExport_Click(object sender, EventArgs e)
 {    
  // creating Excel Application
   Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
  // creating new WorkBook within Excel application
   Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
  // creating new Excelsheet in workbook
   Excel._Worksheet worksheet = null;
  // see the excel sheet behind the program
   app.Visible = false;
  // get the reference of first sheet. By default its name is Sheet1.
   // store its reference to worksheet
   worksheet = workbook.Sheets["Sheet1"];
   worksheet = workbook.ActiveSheet;
  // changing the name of active sheet
   worksheet.Name = "Exported from gridview";
 
  // storing header part in Excel
   for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
   {
   worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
   }
  // storing Each row and column value to excel sheet
   for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
   {
   for (int j = 0; j < dataGridView1.Columns.Count; j++)
   {
     worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
   }
   }
  // save the application
   workbook.SaveAs("d:\\output.xls", Type.Missing, Type.Missing, Type.Missing,
  Type.Missing,
  Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
  Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  // Exit from the application
   app.Quit();
   MessageBox.Show("Excel file created , you can find the file d:\\output.xls");
 }
 
 
kalpana aparnathi replied to devender on 04-Mar-12 06:14 AM
hi,

Try below code:

private void button2_Click(object sender, EventArgs e)
    {
      Excel.Application xlApp ;
      Excel.Workbook xlWorkBook ;
      Excel.Worksheet xlWorkSheet ;
      object misValue = System.Reflection.Missing.Value;
 
      xlApp = new Excel.ApplicationClass();
      xlWorkBook = xlApp.Workbooks.Add(misValue);
      xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
      int i = 0;
      int j = 0;
 
      for (i = 0; i <= dataGridView1.RowCount  - 1; i++)
      {
        for (j = 0; j <= dataGridView1.ColumnCount  - 1; j++)
        {
          DataGridViewCell cell = dataGridView1[j, i];
          xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
        }
      }
 
      xlWorkBook.SaveAs("c1.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
      xlWorkBook.Close(true, misValue, misValue);
      xlApp.Quit();
 
      releaseObject(xlWorkSheet);
      releaseObject(xlWorkBook);
      releaseObject(xlApp);
 
      MessageBox.Show("Excel file created , you can find the file c:\\c1.xls");
    }

Regards,
devender replied to dipa ahuja on 05-Mar-12 02:10 AM
THE FOLLOWING ERROR IS GENERATING AFTER THE COMPILATION OF YOUR CODE... PLZ TRY TO SOLVE IT ... PLZ


Error 1 Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel._Worksheet'. An explicit conversion exists (are you missing a cast?) E:\Project Backup\Suvidha\WindowsFormsApplication1\WindowsFormsApplication1\Create_paybill.cs 128 25 suvidha



Error 2 Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel._Worksheet'. An explicit conversion exists (are you missing a cast?) E:\Project Backup\Suvidha\WindowsFormsApplication1\WindowsFormsApplication1\Create_paybill.cs 129 25 suvidha



Error 3 No overload for method 'SaveAs' takes '11' arguments E:\Project Backup\Suvidha\WindowsFormsApplication1\WindowsFormsApplication1\Create_paybill.cs 148 13 suvidha


Somesh Yadav replied to devender on 05-Mar-12 07:14 AM
Hi devender ,

Sample Code:

   private void button1_Click_1(object sender, EventArgs e)

      {

 

        // creating Excel Application

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

 

 

        // creating new WorkBook within Excel application

        Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);

       

 

        // creating new Excelsheet in workbook

       Microsoft.Office.Interop.Excel._Worksheet worksheet = null;           

       

       // see the excel sheet behind the program

        app.Visible = true;

      

       // get the reference of first sheet. By default its name is Sheet1.

       // store its reference to worksheet

        worksheet = workbook.Sheets["Sheet1"];

        worksheet = workbook.ActiveSheet;

 

        // changing the name of active sheet

        worksheet.Name = "Exported from gridview";

 

       

        // storing header part in Excel

        for(int i=1;i<dataGridView1.Columns.Count+1;i++)

        {

    worksheet.Cells[1, i] = dataGridView1.Columns[i-1].HeaderText;

        }

 

 

 

        // storing Each row and column value to excel sheet

        for (int i=0; i < dataGridView1.Rows.Count-1 ; i++)

        {

          for(int j=0;j<dataGridView1.Columns.Count;j++)

          {

            worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

          }

        }

 

 

        // save the application

        workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);

       

        // Exit from the application

      app.Quit();
      }

 

   

Note this part of code gets data from DataGridView and fills cells.

        // storing Each row and column value to excel sheet

        for (int i=0; i < dataGridView1.Rows.Count-1 ; i++)

        {

          for(int j=0;j<dataGridView1.Columns.Count;j++)

          {

            worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

          }

        }

 

I have taken dataGridView1.Rows.Count-1, because in datagridview it contains empty row at the last. (See in the figure of datagridview.)

for more information refer to the below link.


http://dotnetask.com/Resource.aspx?Resourceid=644

devender replied to Somesh Yadav on 06-Mar-12 08:59 AM
But the Following lines of code giving the associated error with the code... plz try to correct it....

statement 1:    worksheet = workbook.Sheets["Sheet1"]; 

Error 1 Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel._Worksheet'. An explicit conversion exists (are you missing a cast?) E:\Project Backup\Suvidha\WindowsFormsApplication1\WindowsFormsApplication1\Create_paybill.cs 128 25 suvidha



statement 2:   worksheet = workbook.ActiveSheet;

Error 2 Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel._Worksheet'. An explicit conversion exists (are you missing a cast?) E:\Project Backup\Suvidha\WindowsFormsApplication1\WindowsFormsApplication1\Create_paybill.cs 129 25 suvidha

Summi RS replied to devender on 07-Mar-12 03:35 AM
Hello,

The method I use is as following:

    private void button1_Click(object sender, EventArgs e)
 
    {
 
      Workbook workbook = new Workbook();          
 
   //Initialize worksheet
 
      workbook.CreateEmptySheets(1);
 
   Worksheet sheet = workbook.Worksheets[0];
 
      //Insert DataTable to Excel
 
  sheet.InsertDataTable((DataTable) this.dataGridView1.DataSource,true,2,1,-1,-1);
 
      //Set Excel Style
 
    CellStyle Style = workbook.Styles.Add("Style");
 
   Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
 
  Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
 
    Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
 
    Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
 
      Style.Borders.Color = Color.DarkCyan;
 
      Style.Color = Color.Lavender;
 
      Style.Font.FontName = "Calibri";
 
      Style.Font.Size = 12;
 
      CellRange range = sheet.Range["A3:F26"];
 
      range.CellStyleName = Style.Name;
 
      //Set Header Style
 
    CellStyle styleHeader = sheet.Rows[0].Style;
 
    styleHeader.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
 
   styleHeader.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
 
   styleHeader.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
 
   styleHeader.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
 
      styleHeader.Borders.Color = Color.DarkCyan;
 
   styleHeader.VerticalAlignment = VerticalAlignType.Center;
 
      styleHeader.HorizontalAlignment = HorizontalAlignType.Center;
 
    styleHeader.KnownColor = ExcelColors.Cyan;
 
      styleHeader.Font.FontName = "Calibri";
 
      styleHeader.Font.Size = 14;
 
   styleHeader.Font.IsBold = true;
 
      //Set Row Height and Column Width
 
    sheet.AllocatedRange.AutoFitColumns();
 
   sheet.AllocatedRange.AutoFitRows();
 
      sheet.Range["A3:F26"].RowHeight = 16;
 
    sheet.Rows[0].RowHeight = 20;
 
      //Save and Launch File
 
   workbook.SaveToFile("DataImport.xlsx",ExcelVersion.Version2010);
 
   System.Diagnostics.Process.Start(workbook.FileName);
 
 }
 
    private void Form1_Load_1(object sender, EventArgs e)
 
    {
 
      //Load Data from Database to DataGridView
 
      string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;
 
                Data Source=D:\work\VIP.mdb;Persist Security Info=False;";
 
      DataTable dataTable = new DataTable();
 
      using (OleDbConnection conn = new OleDbConnection(connString))
 
      {
 
        conn.Open();
 
        string sql = "select Name,Gender,Birthday,Email,Number,Country from VIP";
 
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, conn);
 
        dataAdapter.Fill(dataTable);
 
      }
 
      this.dataGridView1.DataSource = dataTable;
 
    }
 
  }
 
}

For more details, you can view this post. http://janewdaisy.wordpress.com/2011/12/01/c-import-data-to-excel-through-datagridview/