检测空工作表
检查已填充的单元格
工作表中可以填充一个或多个单元格的值,其中值可以是简单的(文本、数字、日期/时间)或公式或基于公式的值。在这种情况下,很容易检测给定工作表是否为空。我们只需检查Cells.MaxDataRow或Cells.MaxDataColumn属性。如果上述属性返回零或正值,那么表示一个或多个单元格已被填充,但如果其中任何一个属性返回-1,那就表示给定工作表中没有填充任何单元格。
检测空初始化单元格
所有具有值的单元格都会自动初始化,但有可能工作表只有应用了格式的单元格。在这种情况下,Cells.MaxDataRow或Cells.MaxDataColumn属性将返回-1,表示没有填充任何值,但由于单元格格式化而初始化的单元格无法使用此方法进行检测。为了检查工作表是否有已初始化的空单元格,建议在从Cells集合中获取的枚举器上使用IEnumerator.MoveNext方法。如果IEnumerator.MoveNext方法返回true,那么表示给定工作表中有一个或多个已初始化的单元格。
检查形状
可能存在一个工作表中没有填充的单元格,但它可能包含形状和对象,如控件、图表、图像等。如果我们需要检查一个工作表是否包含任何形状,可以通过检查ShapeCollection.Count属性来实现。任何正值都表示在工作表中存在形状。
编程示例
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create an instance of Workbook and load an existing spreadsheet | |
var book = new Workbook(dataDir + "sample.xlsx"); | |
// Loop over all worksheets in the workbook | |
for (int i = 0; i < book.Worksheets.Count; i++) | |
{ | |
Worksheet sheet = book.Worksheets[i]; | |
// Check if worksheet has populated cells | |
if (sheet.Cells.MaxDataRow != -1) | |
{ | |
Console.WriteLine(sheet.Name + " is not empty because one or more cells are populated"); | |
} | |
// Check if worksheet has shapes | |
else if (sheet.Shapes.Count > 0) | |
{ | |
Console.WriteLine(sheet.Name + " is not empty because there are one or more shapes"); | |
} | |
// Check if worksheet has empty initialized cells | |
else | |
{ | |
Aspose.Cells.Range range = sheet.Cells.MaxDisplayRange; | |
var rangeIterator = range.GetEnumerator(); | |
if (rangeIterator.MoveNext()) | |
{ | |
Console.WriteLine(sheet.Name + " is not empty because one or more cells are initialized"); | |
} | |
} | |
} |