Export From DataGridView To Excel-Sheet in C#

using Excel = Microsoft.Office.Interop.Excel;  // Add Refference of Microsoft.Office.Interop.Excel.dll

// The Data that would be in the DataGridView will be Export to Excel Sheet. By
private void ExportToExcel () //Here ‘gridview_newadmission’ is the Name of the DataGridView
{

try
{

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

xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

for (int c = 0; c < gridview_newadmission.ColumnCount; c++)
{

xlWorkSheet.Cells[1, c + 1] = gridview_newadmission.Rows[0].Cells[c].OwningColumn.Name.ToString();
xlWorkSheet.Cells.ColumnWidth = 15;

}

for (int r = 0; r < gridview_newadmission.RowCount; r++)
{

for (int c = 0; c < gridview_newadmission.ColumnCount; c++)
{

DataGridViewCell cell = gridview_newadmission[c, r];
xlWorkSheet.Cells[r + 2, c + 1] = cell.Value;

}

}

FolderBrowserDialog SelectTarget = new FolderBrowserDialog();
SelectTarget.ShowDialog();
string path = SelectTarget.SelectedPath;
if (path != “”)
{

xlWorkBook.SaveAs(path + “\\myData.xls”, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

}
statusMessage.ForeColor = Color.Black;
statusMessage.Text = “Data Saved to ” + path;

 }
catch (Exception)
{}

}

Posts Tagged with…

Write a Comment

Your email address will not be published. Required fields are marked *