Error exporting data to Excel from C #

0

I need to export the data from a DataGriedView to an Excel sheet. I have the following code:

public void exportar(DataGridView dgv)
{
    try
    {
        SaveFileDialog fichero = new SaveFileDialog();
        fichero.Filter = "Excel (*.xlsx)|*xlsx";
        fichero.FileName = "ArchivoExportado";
        if (fichero.ShowDialog() == DialogResult.OK)
        {
            Microsoft.Office.Interop.Excel.Application aplicacion;
            Microsoft.Office.Interop.Excel.Workbook libro;
            Microsoft.Office.Interop.Excel.Worksheet hoja;

            aplicacion = new Microsoft.Office.Interop.Excel.Application();
            libro = aplicacion.Workbooks.Add();
            hoja = (Microsoft.Office.Interop.Excel.Worksheet)libro.Worksheets.get_Item(1);

            for (int i = 0; 1 < dgv.Rows.Count - 1; i++)
            {
                for (int j = 0; 1 < dgv.Columns.Count; j++)
                {
                    if ((dgv.Rows[i].Cells[j].Value == null) == false)
                    {
                        hoja.Cells[i + 1, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
                    }
                }
            }
            libro.SaveAs(fichero.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
            libro.Close(true);
            aplicacion.Quit();
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error"+ex.ToString());
    }
}

When I click on the button Exportar shows me an error:

Line 551 is the if: if ((dgv.Rows[i].Cells[j].Value == null) == false)

I do not know what the problem is.

    
asked by use2105 30.01.2017 в 17:42
source

1 answer

2

Do not use for to go through the rows of the grid use the foreach

int i = 1;
foreach (var row in dgv.Rows)
{
    int j = 1;
    foreach(var col in dgv.Columns)
    {
        if (row.Cells[col.Index].Value != null)
        {
            hoja.Cells[i, j] = row.Cells[col.Imdex].Value.ToString();
        }
        j++;
    }
    i++;
}

I would also recommend that you avoid using the office interop libraries to export to excel, use ones based on open xml as being

ClosedXML - The easy way to OpenXML

This way you will not have problems with COM and do not require office installed to be able to export

    
answered by 30.01.2017 в 22:35