在Excel文档中读取一系列单元格会给我一个错误

本文关键字:错误 一个 文档 Excel 读取 单元格 一系列 | 更新日期: 2023-09-27 17:51:09

我可以读取单个单元格,但我无法读取行或列。使用此代码,我可以读取单个单元格:

xlWorkBook = xlApp.Workbooks.Open(@"C:'Users'bla'blas'users.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "'t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);                
            Console.WriteLine(xlWorkSheet.get_Range("A1", "A1").Value.ToString());

但是当我尝试像这样设置一个范围时:

Console.WriteLine(xlWorkSheet.get_Range(xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[3, 3]).Value.ToString());

我得到这个错误:'object'不包含'get_Range'的定义。

在Excel文档中读取一系列单元格会给我一个错误

试试这个:

xlWorkBook = xlApp.Workbooks.Open(@"C:'Users'bla'blas'users.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "'t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);                
Range range1 = worksheet1.Cells[1, 1];
Range range2 = worksheet1.Cells[3, 3];
Range range = worksheet1.get_Range(range1, range2);
object[,] valArray = range.Value2 as object[,];
int xCount = valArray.GetLength(0);
int yCount = valArray.GetLength(1);
for (int i = 1; i <= xCount; i++)
{
    for (int j = 1; j <= yCount; j++)
    {
        object currentValue = valArray[i, j];
        if (currentValue != null)
        {
            Console.WriteLine(currentValue.ToString());
        }
    }
}
相关文章: