void ExportDGVToExcel(DataGridView dgv) { ExcelClass InformationAboutElements = new ExcelClass(); Font HeadFont = new Font(" Times New Roman ", 12.0f, FontStyle.Bold); int iterator = 0; try { char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); int CurrentCell = 0; InformationAboutElements.NewDocument(); InformationAboutElements.AddNewPageAtTheStart("Данные"); for (int i = 0; i < dgv.Columns.Count; i++) { if (dgv.Columns[i].Visible == true) { InformationAboutElements.SelectCells(alpha[iterator] + (1).ToString(), Type.Missing); InformationAboutElements.SetFont(HeadFont, 0); InformationAboutElements.SetBorderStyle(0, Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin); InformationAboutElements.WriteDataToCell(dgv.Columns[i].HeaderText); for (int j = 0; j < dgv.Rows.Count; j++) { InformationAboutElements.SelectCells(alpha[iterator] + (j + 2).ToString(), Type.Missing); InformationAboutElements.SetFont(HeadFont, 0); InformationAboutElements.SetBorderStyle(0, Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin); InformationAboutElements.setAutoFit(alpha[iterator] + (j + 2).ToString()); InformationAboutElements.WriteDataToCell(dgv[i, j].Value.ToString()); } if (dgv[i, 0].Value.ToString().Length > dgv.Columns[i].HeaderText.Length) { InformationAboutElements.setAutoFit(alpha[iterator] + (2).ToString()); } else { InformationAboutElements.setAutoFit(alpha[iterator] + (1).ToString()); } iterator++; } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } finally { InformationAboutElements.Visible = true; InformationAboutElements.Dispose(); HeadFont.Dispose(); } }