<pre>private void button2_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int x = 1; x < dataGridView3.Columns.Count + 1; x++)
{
xlWorkSheet.Cells[1, x] = dataGridView3.Columns[x - 1].HeaderText;
}
int i = 0;
int j = 0;
for (i = 0; i <= dataGridView3.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView3.ColumnCount - 1; j++)
{
try
{
DataGridViewCell cell = dataGridView3[j, i];
xlWorkSheet.Cells[i + 2, j + 1] = dataGridView3[j, i].Value;
}
catch (Exception ex)
{
MessageBox.Show("Exception Occured while exporting data " + ex.ToString());
}
}
}
Excel.Range oRange = xlWorkSheet.Range["A1", "F3000"];
if (xlApp.Application.Sheets.Count < 2)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Add();
}
else
{
xlWorkSheet = xlApp.Worksheets[2];
}
xlWorkSheet.Name = "Pivot Table";
Excel.Range oRange2 = xlWorkSheet.Cells[1, 1];
Excel.PivotCache oPivotCache = (Excel.PivotCache)xlWorkBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)xlWorkSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
Excel.PivotField oPivotField = (Excel.PivotField)oPivotTable.PivotFields("V");
oPivotField.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
oPivotField.Function = Excel.XlConsolidationFunction.xlSum;
oPivotField.Name = "Somme V";
xlWorkBook.SaveAs("C9.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file C9.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}