一种快速检测给定工作表中是否存在数据的过程,无需实际循环遍历工作表的所有行/列。
对于我当前的流程,我目前正在遍历整个工作表,并且在我的导入中有一些明显的滞后时间。
最佳答案
要避免循环并利用近乎瞬时的执行速度,您可以使用 Excel.WorksheetFunction.CountA
方法,它返回与 =CountA() 工作表函数相同的结果。
假设您的 Excel.Application 引用名为“excelApp”并且您的 Excel.Worksheet 引用名为“worksheet”,您可以在 C# 4.0 中使用如下代码:
// C# 4.0
int dataCount = (int)excelApp.WorksheetFunction.CountA(worksheet.Cells);
if (dataCount == 0)
{
// All cells on the worksheet are empty.
}
else
{
// There is at least one cell on the worksheet that has non-empty contents.
}
在 C# 3.0 及以下版本中,它有点冗长,因为您必须显式提供缺少的可选参数:
// C# 3.0 and below
int dataCount = (int)excelApp.WorksheetFunction.CountA(
worksheet.Cells,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
if (dataCount == 0)
{
// All cells on the worksheet are empty.
}
else
{
// There is at least one cell on the worksheet that has non-empty contents.
}
关于c# - 在VSTO Excel中,如何检测单元格中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347276/