четверг, 21 июля 2011 г.

Exporting a DataGridView to Excel

  1. Add a reference to the ‘Microsoft Office 11.0 Object Library’ to your project from COM components.
  2. Create an object of the ApplicationClass in the Excel namespace
    Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();
  3. Add a new workbook to the object of the Application class. The parameter to the Add method below is the name of the workbook. We are going to provide the name later (while saving the file). So Type.Missing can be used here.
  4. Change properties of the Workbook
    ExcelApp.Columns.ColumnWidth = 30;
  5. Copy the contents of the DataGridView object to the cells of the Excel Application object. In the code below ReportDataGrodView is the name of my DataGridView object.
    for (int i = 0; i < ReportDataGridView.Rows.Count; i++)
        DataGridViewRow row = ReportDataGridView.Rows[i];
        for(int j=0; j< row.Cells.Count; j++)
            ExcelApp.Cells[i+1, j+1] = row.Cells[j].ToString();
  6. Save the workbook at any suitable location. In the code below FileName is a string representing full path to the name of the file. This can be obtained from a SaveFileDialog if you want.
    ExcelApp.ActiveWorkbook.Saved = true;
  7. Exit the Excel Application and free up the resources

Комментариев нет: