Good day, I want to export a DataGridView to an Excel file, I just want to accommodate the columns in a different way to how it appears in my DataGridView. I hope you can help me.
This is my code:
namespace ImportarExcelToDatagridview
{
class Exportar
{
public void ExportarExcel(DataGridView dataGridView1)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
try
{
SaveFileDialog fichero = new SaveFileDialog();
fichero.Filter = "Excel (*.xls)|*.xls";
fichero.FileName = "ArchivoExportado";
if (fichero.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application aplicacion;
Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
aplicacion = new Microsoft.Office.Interop.Excel.Application();
libros_trabajo = aplicacion.Workbooks.Add();
hoja_trabajo =
(Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
//Recorremos el DataGridView rellenando la hoja de trabajo
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if ((dataGridView1.Rows[i].Cells[j].Value == null) == false)
{
hoja_trabajo.Cells[i + 1, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
libros_trabajo.SaveAs(fichero.FileName,
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
libros_trabajo.Close(true);
aplicacion.Quit();
}
}
catch (Exception ex)
{
MessageBox.Show("Error al exportar la informacion debido a: " + ex.ToString());
}
}
}
}