如何使用Python查詢Excel表格中空白和非空白單元格的數量?


在本文中,我們將向您展示如何使用python查詢excel工作表中空白和非空白(已填充)單元格的數量。

假設我們有一個名為**demoTutorialsPoint.xlsx**的excel檔案,其中包含一些隨機資料和一些**空白**單元格。我們將返回excel工作表中空白和非空白(已填充)單元格的數量。

sampleTutorialsPoint.xlsx

運動員姓名 年齡 型別 國家 隊伍 得分 wicket數
Virat Kohli 擊球手 印度 皇家挑戰者班加羅爾 20
34 擊球手 印度 新升太陽海德拉巴 333 140
馬亨德拉·辛格·多尼 39 擊球手 印度 欽奈超級國王 0
Rashid Khan 投球手 古吉拉特巨人 500 130
Hardik Pandya 29 全能選手 古吉拉特巨人 2400 85
David Warner 34 擊球手 澳大利亞 5500 12
Kieron Pollard 35 全能選手 西印度群島 孟買印第安人 0 67
Rohit Sharma 33 擊球手 印度 孟買印第安人 5456 20
Kane Williamson 33 擊球手 新升太陽海德拉巴 3222 5
Kagiso Rabada 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()函式獲取單元格的值。

更新於:2022年8月18日

2K+瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.