c # export data from a datagridview to excel with coumline names

0

I have a problem

Create a class to export the datagridview files to excel but when I export it, only the data appear, I would like the names of the columns to appear as well.

this is the code used.

    public void ExportarDataGridViewExcel(DataGridView grd)
    {
        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 < grd.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < grd.Columns.Count; j++)
                    {
                        if ((grd.Rows[i].Cells[j].Value == null) == false)
                        {
                            hoja_trabajo.Cells[i + 1, j + 1] = grd.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());
        }
    
asked by tonii zavala 24.01.2018 в 08:15
source

1 answer

2

To get the header of the columns you need to access the Name property of the columns:

grd.Columns[i].Name

In your code you can initialize the headers by iterating over the columns:

for (int i = 0; i < grd.Columns.Count - 1; i++)
{
    hoja_trabajo.Cells[0, i] = grd.Columns[i].Name
}

I have not tried the code, but I hope it will help you.

    
answered by 24.01.2018 в 10:26