Friday, 2 October 2015

Export Datagridview to Excel in VS 2012

DataSet ds=new DataSet();
ds=LoadData(qry);

            // 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 = "Students List";


            // storing header part in Excel
            for (int i = 1; i < ds.Tables[0].Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = ds.Tables[0].Columns[i - 1].ColumnName.ToString();
            }



            // storing Each row and column value to excel sheet
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = ds.Tables[0].Rows[i][j].ToString();
                }
            }


            // save the application
            workbook.SaveAs("d:\\output.xls");


Befor that add Microsoft.Office.Interop.Excel dll in reference


if (dataGridView1.Rows.Count > 0)
            {
                Microsoft.Office.Interop.Excel.ApplicationClass XcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                XcelApp.Application.Workbooks.Add(Type.Missing);

                for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
                {
                    XcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
                }
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        XcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                }

                XcelApp.Columns.AutoFit();
                XcelApp.Visible = true;

            }
            else
            {
                MessageBox.Show("No Data to Export");
            }
          

VS 2008 Exporting Datagrid to Excel