Python 如何在Excel表中找到空白单元格和非空白单元格的数量
在本文中,我们将向您展示如何使用python在excel工作表中找到空白单元格和非空白(已填充)单元格的数量。
假设我们已经获取了一个名为 demoTutorialsPoint.xlsx 的Excel文件,其中包含一些随机数据和一些空白单元格。我们将返回Excel工作表中空白单元格和非空白(已填充)单元格的数量。
sampleTutorialsPoint.xlsx
球员姓名 | 年龄 | 类型 | 国家 | 球队 | 得分 | 球员数 |
---|---|---|---|---|---|---|
维拉特·科利 | 打击手 | 印度 | 皇家挑战者班加罗尔 | 20 | ||
34 | 打击手 | 印度 | 太阳升海得拉巴 | 333 | 140 | |
慕亨德拉·辛格·多尼 | 39 | 打击手 | 印度 | 钟普尔超级国王 | 0 | |
拉希德·可汗 | 玩家 | 古吉拉特泰坦 | 500 | 130 | ||
哈迪克·潘迪亚 | 29 | 全能选手 | 古吉拉特泰坦 | 2400 | 85 | |
大卫·华纳 | 34 | 接击手 | 澳大利亚 | 5500 | 12 | |
奎恩·波拉德 | 35 | 全能选手 | 西印度群岛 | 孟买印地安人 | 0 | 67 |
罗希特·夏尔马 | 33 | 接击手 | 印度 | 孟买印地安人 | 5456 | 20 |
凯恩·威廉姆森 | 33 | 打击手 | 孟买天王星 | 3222 | 5 | |
卡吉索·拉巴达 | 29 | 投球手 | 南非 | 幸运首都 | 335 | 1 |
步骤
以下是执行所需任务的算法/步骤:
- 使用import关键字,导入 xlrd模块 (使用xlrd模块读取电子表格中的数据。它具有读取、写入和更改数据的能力。此外,用户可能需要遍历多个工作表以根据特定条件获取数据,或更改特定的行和列等。使用xlrd模块提取电子表格中的数据)。
pip install xlrd
- 创建一个变量来存储Excel表格中空单元格的计数。
-
创建另一个变量来存储Excel表格中非空单元格的计数。
-
将两个计数变量初始化为0。
-
创建一个变量来存储输入Excel文件的路径。
-
要创建一个工作簿对象,将输入的Excel文件作为参数传递给xlrd模块的open_workbook()函数(打开工作簿)。
-
使用sheet_by_index()方法(打开指定索引的工作表),打开给定工作簿中的第一个工作表(这里0表示第一个工作表)。
-
使用for循环遍历工作表中的所有行。使用nrows属性获取总行数。
-
使用嵌套的for循环,使用另一个嵌套的for循环遍历工作表中的所有列。使用ncols属性获取总列数。
-
使用cell_value()函数(给出指定行和列的单元格值)和if条件语句判断单元格是空还是非空。
-
如果是空单元格,则将空单元格计数加1。
-
否则,将非空单元格计数加1。
-
打印在给定的输入Excel文件中找到的空单元格的计数。
-
打印在给定的输入Excel文件中找到的非空单元格的计数。
示例
以下程序打印在给定的输入Excel文件中找到的空白和非空白单元格的计数:
import xlrd
# storing the count of Empty cells
emptyCells=0
# storing the count of Non-empty cells
nonEmptycells=0
# input excel file path
inputExcelFile ="sampleTutorialsPoint.xlsx"
# creating a workbook
newWorkbook =xlrd.open_workbook(inputExcelFile)
# creating a first worksheet
firstWorksheet=newWorkbook.sheet_by_index(0)
# Traversing in all the rows of the worksheet
# (nrows is used to get the number of rows)
for each_row in range (firstWorksheet.nrows):
# Traversing in all the columns of the worksheet
# (ncols is used to get the number of columns)
for each_column in range (firstWorksheet.ncols) :
# Checking whether the cell is a blank cell
if (firstWorksheet.cell_value(each_row, each_column)==""):
# Incrementing empty cells count by 1, if it is a blank cell
emptyCells+=1
else :
# Else Incrementing Non-empty cells count by 1
nonEmptycells+=1
# Printing the count of empty cells
print("Empty cells count = ", emptyCells)
# Printing the count of Non-empty cells
print("Non-empty cells count = ", nonEmptycells)
输出
在执行后,上述程序将生成以下输出-
Empty cells count = 10
Non-empty cells count = 67
我们在程序中使用了一个带有一些虚假数据的示例Excel文件。该Excel文件中有一些空白单元格。我们使用了两个变量来计算空白单元格和非空白单元格的数量,并使用for循环逐个单元格遍历Excel文件,检查它是否为空白单元格,并打印出空白单元格和非空白单元格的计数。
结论
我们学习了如何使用xlrd模块将Excel文件作为工作簿获取,并将指定的工作表作为工作表获取。我们还学习了如何逐个单元格遍历Excel文件以及如何使用cell_value()函数获取单元格的值。