0

我从 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);`

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

 `xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];`

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

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

希望你会知道答案..

4

1 回答 1

5

试试这个:

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

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

于 2012-10-19T04:24:52.700 回答