簡體   English   中英

使用 openpyxl 在 excel 工作表中查找隱藏列時缺少列

[英]Columns missing when looking for hidden columns in excel worksheet using openpyxl

我正在嘗試僅讀取 excel 工作表中的非隱藏列,並使用相同的內容創建 dataframe。 使用 pandas 和 openpyxl。

Openpyxl 在使用 column_dimension 時沒有找到連續的隱藏列。 如果在創建隱藏 state 時有分組,則只返回第一個隱藏列。 例如,如果列 E 和 F 作為一個組被隱藏,則 E 已隱藏設置為 true,並且列列表中缺少 F。 因此,我所做的是獲取工作表中所有可能的列和所有列之間的差異,從而得到丟失的隱藏列。 然后將其與具有隱藏 state 的那些連接以獲得“所有”隱藏列。

但是正在發生的事情是一些不在 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

似乎ws.column_dimensions.items()沒有返回工作表中所有列的完整列表。 通過遍歷工作表中的所有列並測試該列是否隱藏,我能夠找到所有隱藏的列。 本答案中所述, Excel 合並了分組列的單元格定義,但您可以使用max屬性查找該組中的最后一列。 因此,一旦找到隱藏列,您可以使用max屬性輕松找到該組的 rest。

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM