Before writing the code for MS Excel export you need to add Excel Interoperability service reference to you'r application.
Click on References -> Add Reference
Select the Interoperability service reference for MS Excel
Add below method to your Export button click event. Here i'm assuming that you have already done data loading part for the DataGridView.
public void DataTableToExcel()
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
// 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 = "Employees";
// storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
string values = string.Empty;
values = dataGridView1.Rows[i].Cells[j].Value.ToString();
worksheet.Cells[i + 2, j + 1] = values;
}
}
}
finally
{
//Release the resources
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
}
No comments:
Write comments