Click here to Skip to main content
15,071,262 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i am using this code for export datagridview to excel....but 2 error is showing on it....


1.cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel_worksheet'.An explicit conversion exists(are you missing a cast?)

{

 // 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();
}



please tell me how to solve this error........
Posted
Updated 16-Apr-12 1:51am
v2
Comments
   
Not a question. Not enough information. What exception or error do you have. Format the code, indicate it. Please use "Improve question" above.
--SA
ZurdoDev 20-Mar-12 11:20am
   
What line of code is it failing on?
hitech_s 16-Apr-12 7:51am
   
<pre> tags added

This is a lie:
C#
// creating new Excelsheet in workbook 
               Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

The code above does not create a new worksheet.

The error message gives you a very heavy hint: Are you missing a cast?


C#
// You have:
    worksheet = workbook.Sheets["Sheet1"];
    worksheet = workbook.ActiveSheet;
// Try this:
    worksheet = (Microsoft.Office.Interop.Excel._Worksheet) workbook.Sheets["Sheet1"];
    worksheet = (Microsoft.Office.Interop.Excel._Worksheet) workbook.ActiveSheet;

Also, notice that "Sheet1" will be called something else in non-English versions of Excel.

Hope this helps,
Pablo.
   
v2
First of all add References or dll in solution explorer as following

Microsoft.Office.Introp.Excel
Microsoft.Vbe.Introp


Write on Top of Coding file

C#
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;




and Place following coding on button click



**** Coding ****


C#
if (dataGridView1.Rows.Count > 0)
            {

                try
                {
                    Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();

                    ExcelApp.Application.Workbooks.Add(Type.Missing);

                    Excel.Application xlApp;
                    Excel.Workbook xlWorkBook;
                    Excel.Worksheet xlWorkSheet;
                    object misValue = System.Reflection.Missing.Value;

                    // Change properties of the Workbook 

                    ExcelApp.Columns.ColumnWidth = 20;

                    xlApp = new Excel.Application();
                    xlWorkBook = xlApp.Workbooks.Add(misValue);
                    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                    // Storing header part in Excel

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

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

                    }



                    // Storing Each row and column value to excel sheet

                    for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
                    {
                        for (int j = 0; j <= dataGridView1.ColumnCount - 1; j++)
                        {
                            DataGridViewCell cell = dataGridView1[j, i];
                            ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                        }
                    }

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

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

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

                    //    }

                    //}

                    xlWorkBook.SaveAs("MasterReport.xls", Excel.XlFileFormat.xlWorkbookDefault, 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);

                    //ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Report.xls");

                    //ExcelApp.ActiveWorkbook.Saved = true;

                    //ExcelApp.Quit();

                    MessageBox.Show("Excel file created , you can find the file in 'My Documents' Drive Name As MasterReport.xls", "Converted", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
                }

            }
            else
            {
                MessageBox.Show("No Record Found to Convert, Access Denied", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);


            }
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }



I am sure give guaranty to run it.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900