1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
public static void ExportADataGridViewInExcelFile(DataGridView datagrid, string FileName)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp != null)
{
Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)(xlApp.Workbooks.Add(Missing.Value));
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
object misValue = System.Reflection.Missing.Value;
int i = 1;
foreach (DataGridViewColumn col in datagrid.Columns)
{
if (col.Visible)
{
ws.Cells[1, col.DisplayIndex + 1] = col.HeaderText;
i++;
}
}
Microsoft.Office.Interop.Excel.Range range = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, i]);
range.Font.Bold = true;
int k = 2;
foreach (DataGridViewRow row in datagrid.Rows)
{
foreach (DataGridViewColumn col in datagrid.Columns)
{
if (col.Visible)
{
ws.Cells[k, col.DisplayIndex + 1] = row.Cells[col.Index].Value;
}
}
k++;
}
wb.SaveAs(FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
wb.Close(true, misValue, misValue);
xlApp.Workbooks.Close();
xlApp.Quit();
if (range != null) { Marshal.ReleaseComObject(range); }
if (ws != null) { Marshal.ReleaseComObject(ws); }
if (wb != null) { Marshal.ReleaseComObject(wb); }
if (xlApp != null) { Marshal.ReleaseComObject(xlApp); }
range = null;
ws = null;
wb = null;
xlApp = null;
GC.Collect();
MessageBox.Show("Exportation terminée.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else MessageBox.Show("Erreur.\nVeuillez vérifier que Excel est installé sur votre machine.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
} |
Partager