using ExcelApplication = Microsoft.Office.Interop.Excel.Application;
public void ExporterGridVersExcel(DataGridView dgView, String unFichier, string strEnteteDeFichier) { int i = 0; int j = 0; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//ici je déclare direct excel Microsoft.Office.Interop.Excel.Workbook exbook = (Microsoft.Office.Interop.Excel.Workbook)excel.Workbooks.Add(Missing.Value); Microsoft.Office.Interop.Excel.Worksheet exsheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet; excel.Visible = true; //try //{ //Mise en forme de l'en-tête de la feuille Excel exsheet.Cells[1, 1] = strEnteteDeFichier; Microsoft.Office.Interop.Excel.Range r = exsheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value); r.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic; r.Font.Bold = true; r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value); r.EntireColumn.AutoFit();//Fin de la mise en forme de l'en-tête. foreach (DataGridViewColumn ch in dgView.Columns) { if (exsheet.Cells[2, 2] != null) { r = exsheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value); exsheet.Cells[2, i + 1] = ch.Name.Trim(); r.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic; r.Font.Bold = true; r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value); r.EntireColumn.AutoFit(); i++; } } j = 3; foreach (DataGridViewRow uneLigne in dgView.Rows) { i = 1; foreach (DataGridViewColumn uneColonne in dgView.Columns) { if (exsheet.Cells[j, i] != null) { r = exsheet.get_Range(Convert.ToChar(65 + i - 1).ToString() + j.ToString(), Missing.Value); if (uneLigne.Cells[uneColonne.Name].Value != null) exsheet.Cells[j, i] = "'" + uneLigne.Cells[uneColonne.Name].Value.ToString().Trim(); r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value); r.EntireColumn.AutoFit(); i++; } } exsheet.Columns.AutoFit(); j++; } exsheet.SaveAs(unFichier, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); //excel.Quit(); //} //catch (Exception ex) //{ // throw (ex); //} //finally //{ //excel.Quit(); //} }
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre question