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

Moh*_*uur 7 .net c# excel vsto office-2007

我想知道是否有人知道如何快速检测给定工作表中是否有数据,而没有实际循环遍历工作表的所有行/列来解决这个问题.

我正在编写一个导入器,它将数据直接导入活动工作表(如果尚未修改),或创建一个新工作表并导入其中.我目前正在遍历整个工作表,导入时有一些明显的滞后时间.

我将不胜感激任何帮助.谢谢!

Mik*_*lum 13

为了避免循环并利用几乎瞬时的执行速度,您可以使用该Excel.WorksheetFunction.CountA方法,该方法返回与= CountA()工作表函数相同的结果.

假设您的Excel.Application引用被命名为"excelApp"并且您的Excel.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.
}
Run Code Online (Sandbox Code Playgroud)

在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.
}
Run Code Online (Sandbox Code Playgroud)

我认为这应该为你做到!

麦克风