Im reading an Excel document from C# Windows Form.. There are 25 worksheets in Excel Workbook.. i can read 1st worksheet successfully.. But when i change it to worksheet 2.. it won't working at all.. Im not using OLEDB..
I want to read 100 Row in every sheet.. following is my code...
` dt.Columns.Add("Amount", typeof(double));
dt.Columns.Add("ChequeNo", typeof(int));
dt.Columns.Add("month", typeof(int));
int AmountRow = 100;
int ChequeNoRow = 101;
int Column = 3;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[2];\\This place is the changing worksheets
range = xlWorkSheet.UsedRange;
double chequeAmount;
double chequeNo;
for (int i = Column; i < 15; i++)
{
chequeAmount = (double)(range.Cells[AmountRow, i] as Excel.Range).Value2;
chequeNo = (double)(range.Cells[ChequeNoRow, i] as Excel.Range).Value2;
if (chequeNo != 0.0)
{
dt.Rows.Add(Convert.ToDouble(chequeAmount), Convert.ToInt32(chequeNo), i);
}
}
dataGridView1.DataSource = dt;
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);`
releaseObject methods are not here.. those working perfectly...
`xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];`
This is how i change my worksheets.. The following line gives an exception..[Null point Exception]
chequeAmount = (double)(range.Cells[AmountRow, i] as Excel.Range).Value2;
Hope you'll know answers..
Try this instead:
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];
The Sheets
property can include non-worksheet sheets, which could be the issue in your scenario.