我正在嘗試僅讀取 excel 作業表中的非隱藏列并使用相同的資料框創建資料框。使用 pandas 和 openpyxl。
Openpyxl 在使用 column_dimension 時沒有找到連續的隱藏列。如果創建隱藏狀態有分組,則只回傳第一個隱藏列。例如,如果列 E 和 F 作為一個組被隱藏,則 E 已隱藏設定為 true,并且列串列中缺少 F。因此,我所做的是獲取作業表中所有可能的列和所有列之間的差異,從而得到丟失的隱藏列。然后將其與具有隱藏狀態的那些連接以獲得“所有”隱藏列。
但是正在發生的事情是一些不在 column_dimensions 中的列在實際的 excel 表中沒有顯示為隱藏。不知道如何僅獲取真正的“隱藏”列的串列。
這是我寫的代碼
# reading the file and worksheet
wb = load_workbook(path, read_only = False)
ws = wb['Overview']
mx_col = ws.max_column
col_indx =[]
for i in range(1,mx_col 1):
num = get_column_letter(i)
col_indx.append(num)
hid_cols = []
col_vals = []
for col, dimension in ws.column_dimensions.items():
col_vals.append(col)
if dimension.hidden:
hid_cols.append(col)
diff = list(set(col_indx) - set(col_vals))
hidden_columns = diff hid_cols
uj5u.com熱心網友回復:
似乎ws.column_dimensions.items()沒有回傳作業表中所有列的完整串列。通過遍歷作業表中的所有列并測驗該列是否隱藏,我能夠找到所有隱藏的列。如本答案中所述,Excel 合并了分組列的單元格定義,但您可以使用該max屬性來查找該組中的最后一列。因此,一旦找到隱藏列,您就可以使用該max屬性輕松找到該組的其余部分。
import openpyxl as op
from openpyxl.utils import get_column_letter
wb = op.load_workbook("Date_format.xlsx")
ws = wb["Sheet1"]
max_col = ws.max_column
cols = [get_column_letter(i) for i in range(1, max_col 1)]
# Find hidden columns
hidden_cols = []
last_hidden = 0
for i, col in enumerate(cols):
# Column is hidden
if ws.column_dimensions[col].hidden:
hidden_cols.append(col)
# Last column in the hidden group
last_hidden = ws.column_dimensions[col].max
# Appending column if more columns in the group
elif i 1 <= last_hidden:
hidden_cols.append(col)
visible_cols = [col for col in cols if col not in hidden_cols]
print("Columns:\t\t", cols)
print("Hidden columns:\t", hidden_cols)
print("Visible columns:", visible_cols)
>>>
Columns: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
Hidden columns: ['B', 'D', 'E', 'G', 'H', 'I']
Visible columns: ['A', 'C', 'F', 'J']
或者更嵌套的 for 回圈版本(不那么 Pythonic):
for i, col in enumerate(cols):
if ws.column_dimensions[col].hidden:
for col_num in range(ws.column_dimensions[col].min, ws.column_dimensions[col].max 1):
hidden_cols.append(get_column_letter(col_num))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417858.html
標籤:
