public static bool ExportarDataGridAExcel(DataGridView dgv) { try { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Workbooks.Add(true); int columnIndex = 0; foreach (DataGridViewColumn column in dgv.Columns) { columnIndex++; excel.Cells[1, columnIndex] = column.HeaderText; excel.Columns[columnIndex].ColumnWidth = column.Width / 7; var ran = excel.Columns[columnIndex]; } int rowIndex = 1; foreach (DataGridViewRow row in dgv.Rows) { rowIndex++; columnIndex = 0; for (columnIndex = 0; columnIndex < dgv.Columns.Count; columnIndex++) { //columnIndex++; object obj = row.Cells[columnIndex].Value; DataGridViewCell cell = row.Cells[columnIndex]; Microsoft.Office.Interop.Excel.Range range = excel.Cells[rowIndex + 1, columnIndex + 1]; int c; if ((c = System.Drawing.ColorTranslator.ToOle(row.DefaultCellStyle.BackColor)) != 0) { range.Interior.Color = c; range.Font.Color = System.Drawing.ColorTranslator.ToOle(row.DefaultCellStyle.ForeColor); } if (row.DefaultCellStyle.Font != null) { if (row.DefaultCellStyle.Font.Bold) { range.Font.FontStyle = "Bold"; } } if (obj == null) { continue; } string dato = obj.ToString(); DateTime val; if (dato.Length >= 10 && DateTime.TryParse(dato, out val) == true) { dato = val.ToString("yyyy/MM/dd"); } range.Value = dato; if (dgv.Columns[columnIndex].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleRight) { range.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight; } else { range.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft; } //excel.Cells[rowIndex + 1, ColumnIndex] } } excel.Visible = true; return(true); } catch (Exception ex) { Utiles.WriteErrorLog(ex.Message); Mensajes.msgErrorExcel(); return(false); } }