c# - 在VSTO Excel中,如何检测单元格中的数据?

标签 c# .net excel vsto office-2007

一种快速检测给定工作表中是否存在数据的过程,无需实际循环遍历工作表的所有行/列。

对于我当前的流程,我目前正在遍历整个工作表,并且在我的导入中有一些明显的滞后时间。

最佳答案

要避免循环并利用近乎瞬时的执行速度,您可以使用 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/

相关文章:

c# - .NET Framework SDK 如何与可用的目标框架相关联?

c# - 如何检测是否调试

c# - File.Copy() 和符号链接(symbolic link)

c# - 提供程序 'SqlServer-20' 没有元数据信息

.net - 默认 VS 对象可视化工具中的 LINQ to SQL 分组错误

c# - 在 C#/VB.NET 或 C++ Win32 中启用/禁用 Aero

c# - 在哪里/如何存储或处理大量自定义异常?

excel - 单击后将 ActiveX 命令按钮颜色更改回之前的颜色

python - Pandas Left Merge 与 xlsx 和 CSV 在输出中生成空值列

vba - 确定多个单元格的 Excel VBA 代码范围