我想在一个文件中读取多个excel表而不在C#中使用OLEDB

tha*_*ksh 0 c# excel import-from-excel visual-studio-2008

我正在从C#Windows窗体中读取Excel文档..在Excel工作簿中有25个工作表..我可以成功读取第一个工作表..但是当我将其更改为工作表2时...它将无法正常工作..我不使用OLEDB ..

我想在每张表中阅读100行..以下是我的代码......

`       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);`
Run Code Online (Sandbox Code Playgroud)

releaseObject方法不在这里..那些工作完美......

 `xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];`
Run Code Online (Sandbox Code Playgroud)

这是我改变我的工作表的方式..以下行给出了一个异常.. [Null point Exception]

chequeAmount = (double)(range.Cells[AmountRow, i] as Excel.Range).Value2;

希望你能知道答案..

MrB*_*lue 5

试试这个:

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];

Sheets属性可以包含非工作表工作表,这可能是您的方案中的问题.