检测空工作表

检查已填充的单元格

工作表中可以填充一个或多个单元格的值,其中值可以是简单的(文本、数字、日期/时间)或公式或基于公式的值。在这种情况下,很容易检测给定工作表是否为空。我们只需检查Cells.max_data_rowCells.max_data_column属性。如果上述属性返回零或正值,那么表示一个或多个单元格已被填充,但如果其中任何一个属性返回-1,那就表示给定工作表中没有填充任何单元格。

检测空初始化单元格

所有有值的单元格都会自动初始化,但也存在工作表中只有格式应用的单元格。在这种情况下,Cells.max_data_rowCells.max_data_column 属性会返回 -1,表示没有已填充值,但由于单元格格式造成的已初始化单元格无法通过此方法检测。要检查工作表是否有空的已初始化单元格,建议使用从 Cells 集合中获取的枚举器调用 IEnumerator.MoveNext 方法。如果方法返回 true,意味着工作表中存在一个或多个已初始化的单元格。

检查形状

某个工作表可能没有任何已填充的单元格,但可能包含形状和对象,如控件、图表、图片等。如果需要检查工作表中是否包含任何形状,可以通过检查 ShapeCollection 元素来实现。任何正值都表示工作表中存在形状。

编程示例

from aspose.cells import Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# The path to the documents directory.
dataDir = RunExamples.GetDataDir(".")
# Create an instance of Workbook and load an existing spreadsheet
book = Workbook(dataDir + "sample.xlsx")
# Loop over all worksheets in the workbook
for i in range(len(book.worksheets)):
sheet = book.worksheets[i]
# Check if worksheet has populated cells
if sheet.cells.max_data_row != -1:
print(sheet.name + " is not empty because one or more cells are populated")
else:
if len(sheet.shapes) > 0:
print(sheet.name + " is not empty because there are one or more shapes")
else:
range = sheet.cells.max_display_range
rangeIterator = range.get_enumerator()
if rangeIterator.__next__():
print(sheet.name + " is not empty because one or more cells are initialized")