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.