Hey Developers
I have made an application that takes data from sql 2005 using a stored procedure and displays them on a datagridview. And then now i have written code to export the data to an excel file using Microsoft Interop and Excel Core Services.
When i click on the export button it throws a System.ArgumentOutOfRangeException error, which says index was out of range. Must be non negative and less than the size of the collection.
System.Windows.Forms.DataGridviewCellCollection.get_Item(Int32 index)
Here's my Code:
Excel._Application xApp;
Excel.Workbook xWork;
Excel.Worksheet xSheet;
object misValue = System.Reflection.Missing.Value;
xApp = new Excel.ApplicationClass();
xWork = xApp.Workbooks.Add(misValue);
xSheet = (Excel.Worksheet)xWork.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i <= dtGrid.Rows.Count; i++)
{
DataGridViewRow row = dtGrid.Rows[i];
for (j = 0; j <= row.Cells.Count; j++)
{
xApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
xWork.SaveAs(misValue, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xWork.Close(true, misValue, misValue);
xApp.Quit();
releaseObject(xSheet);
releaseObject(xWork);
releaseObject(xApp);