如何使用 Python 和 Selenium 獲取工作表中已佔用行和列的最大數量?
我們可以在 Selenium 中獲取工作表中已佔用行和列的最大數量。Excel 是一種電子表格,以 .xlsx 副檔名儲存。一個 Excel 工作簿包含多個工作表,每個工作表都包含行和列。
在所有工作表中,當我們訪問特定的工作表時,它被稱為活動工作表。工作表中的每個單元格都有一個唯一的地址,它是行號和列號的組合。
列號從字母字元 A 開始,行號從數字 1 開始。一個單元格可以包含多種型別的值,它們是工作表的主要組成部分。
要在 Python 中使用 Selenium 處理 Excel,我們需要藉助 OpenPyXL 庫。此庫負責對 Excel 進行讀寫操作,副檔名如 xlsx、xlsm、xltm、xltx。
要安裝 OpenPyXL 庫,我們必須執行命令 **pip install openpyxl**。這是因為 OpenPyXL 不是 Python 的預設庫。之後,我們應該在程式碼中 **import openpyxl**,然後我們就可以與 Excel 進行互動了。
要獲取工作表中已佔用行的數量,首先我們需要透過指定其所在路徑載入整個工作簿。這是透過 load_workbook() 方法實現的。接下來,我們需要藉助 active 方法識別所有工作表中的活動工作表。
最後,我們需要使用 max_row 方法,它會返回已佔用行數。請注意,此方法需要與工作表級物件一起使用。
我們需要使用 max_column 方法,它會返回已佔用列數。請注意,此方法需要與工作表級物件一起使用。
語法
wrkbk = load_workbook("C:\work\SeleniumPython.xlsx")
# to identify the active sheet
sh = wrkbk.active
# identify the number of occupied rows
sh.max_row
# identify the number of occupied rows
sh.max_column示例
計算已佔用行和列最大數量的程式碼實現。
import openpyxl
# load excel with its path
wrkbk = load_workbook("C:\work\SeleniumPython.xlsx")
# to get the active work sheet
sh = wrkbk.active
# get the value of row 2 and column 3
c=sh.cell(row=2,column=3)
# to set the value in row 2 and column 3
sh.cell(row=2,column=3).value = "Tutorialspoint"
# to print the value in console
print(sh.cell(row=2,column=3).value)
# to print the maximum number of occupied rows in console
print(sh.max_row)
# to print the maximum number of occupied columns in console
print(sh.max_column)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP