San Diego Website design home Contact Us Client Login


Tuesday, March 04, 2008

Export DataGridView to Excel

 private void ExportGridView()
        {

           Excel.Application m_objExcel = new Excel.Application();
           Excel.Workbooks m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
           Excel._Workbook m_objBook = (Excel._Workbook)(m_objBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet));
           Excel.Sheets m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
           Excel._Worksheet m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));     

            try
            {
                int x;
                int y;
                int c;
                int cc = this.dataGridView1.ColumnCount;
                int rc = this.dataGridView1.RowCount;
                for (c = 0; c < cc; c++)
                {
                    m_objSheet.Cells[1, c + 1] = this.dataGridView1.Columns[c].HeaderText;
                }
                for (x = 0; x < (rc - 1); x++)
                {
                    for (y = 0; y < cc; y++)
                    {
                        m_objSheet.Cells[x + 2, y + 1] = this.dataGridView1.Rows[x].Cells[y].Value.ToString();
                    }
                }
                m_objExcel.Visible = true;
                m_objExcel.UserControl = true;
               
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            MessageBox.Show("Data Exported");
          

        }

Comments

Name
URL
Email
Email address is not published
Remember Me
Comments

CAPTCHA
Write the characters in the image above

San Diego Website Design
San Diego Flash Design
Testimonials
Contact Us
Support
Privacy Policy
Site Map