我的 Excel 有数百万条记录(约 110 万条),当我尝试使用 WorkSheet.Cells[row,cloumn] 逐个单元格读取时,速度非常慢。
相反,如果我使用的话,WorkSheet.Cells.CheckCell(row, column) 性能非常好。
您能否告诉我这两个 API 之间的区别
最佳答案
Worksheet.Cells.CheckCell() 是检查单元格是否存在的最正确方法。
如果单元格不存在,CheckCell 方法不会实例化该单元格。另一方面,如果单元不存在,Cells[r, c] 将实例化该单元。
这意味着,
CheckCell can return null or cell object.
But Cells[r, c] will never return null and will always return cell object.
由于 Cells[r, c] 总是返回 cell 对象,如果它不存在,它将创建它,这就是为什么,它会影响性能。如果您想迭代工作表中的所有现有单元格而不创建新单元格,请使用 Worksheet.Cells.GetEnumerator() 方法。
请参阅以下示例代码、其注释和控制台输出以供引用。
C#
//Create a workbook
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.Worksheets[0];
//At the moment, Cell B4 does not exist
//Therefore check cell will return null
Cell cell = ws.Cells.CheckCell(3, 1);
Console.WriteLine(cell == null); //<<<<<<<<<< It will print - True
//After this statement, cell B4 will be instantiated and it will exist
var o = ws.Cells[3, 1];
//Now check cell will not return null, but it will return cell B4
cell = ws.Cells.CheckCell(3, 1);
Console.WriteLine(cell == null);//<<<<<<<<<< It will print - False
控制台输出
True
False
更新 - 1
请参阅以下示例代码、其注释和控制台输出。它说明了 GetEnumerator() 方法也返回非空和空单元格。
C#
//Create a workbook
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.Worksheets[0];
//Create empty cells
//Cell A4, B6, C8 and D10 all are empty
var o = ws.Cells["A4"];
o = ws.Cells["B6"];
o = ws.Cells["C8"];
o = ws.Cells["D10"];
//Get cells enumerator
var i = ws.Cells.GetEnumerator();
//Iterate all cells
while(i.MoveNext())
{
Cell cell = i.Current as Cell;
//Print cell name
Debug.WriteLine(cell.Name);
}
控制台输出
A4
B6
C8
D10
注意:我在 Aspose 担任开发人员传播者
关于excel - Aspose 检查单元格和 Aspose WorkSheet.Cells[r,c],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863876/