2
Reply

Error exporting datagridview to Excel

Pedro Brito

Pedro Brito

May 14 2013 9:10 AM
1.1k
Hello all , i need help with a code that export datagridview to excel
So my problem is that when i click in the export button it just show the columns name and not the data that is on the datagridview.

Here is my code

public static void ExportDataGridViewTo_Excel12(DataGridView itemDataGridView)
        {
            Excel_12.Application oExcel_12 = null;                //Excel_12 Application
            Excel_12.Workbook oBook = null;                       // Excel_12 Workbook
            Excel_12.Sheets oSheetsColl = null;                   // Excel_12 Worksheets collection
            Excel_12.Worksheet oSheet = null;                     // Excel_12 Worksheet
            Excel_12.Range oRange = null;                         // Cell or Range in worksheet
            Object oMissing = System.Reflection.Missing.Value;

            // Create an instance of Excel_12.
            oExcel_12 = new Excel_12.Application();

            // Make Excel_12 visible to the user.
            oExcel_12.Visible = true;

            // Set the UserControl property so Excel_12 won't shut down.
            oExcel_12.UserControl = true;

            // System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");

            // Add a workbook.
            oBook = oExcel_12.Workbooks.Add(oMissing);

            // Get worksheets collection 
            oSheetsColl = oExcel_12.Worksheets;

            // Get Worksheet "Sheet1"
            oSheet = (Excel_12.Worksheet)oSheetsColl.get_Item(1);

            // Export titles
            for (int j = 0; j < itemDataGridView.Columns.Count; j++)
            {
                oRange = oSheet.Cells[1, j + 1] as Excel_12.Range;
                oRange.Value2 = itemDataGridView.Columns[j].HeaderText;
            }

            // Export data
            for (int i = 0; i < itemDataGridView.Rows.Count - 1; i++)
            {
                for (int j = 0; j < itemDataGridView.Columns.Count; j++)
                {
                    oRange = oSheet.Cells[i + 2, j + 1] as Excel_12.Range;
                    oRange.Value2 = itemDataGridView.Rows[i].Cells[j].Value;

                }
            }

            // Release the variables.
            //oBook.Close(false, oMissing, oMissing);
            oBook = null;

            //oExcel_12.Quit();
            oExcel_12 = null;

            // Collect garbage.
            GC.Collect();
        }
 

Answers (2)