获取xlsx文件中合并单元格的正确背景色

0 投票
1 回答
39 浏览
提问于 2025-04-12 15:32

我现在正在尝试从一个xlsx文件中提取单元格的背景颜色:

我从其他StackOverflow帖子中找到了两种方法:

1)

wb = load_workbook(excel_file, data_only = True)
sh = wb[wb.sheetnames[0]]
rows = sh.max_row 
cols = sh.max_column
bckg_color = np.empty(shape=(rows, cols), dtype=object)
for i in range(1,rows+1):
    for j in range(1,cols+1):
        cell = sh.cell(column=j, row=i)
        color_in_hex = cell.fill.start_color.index
        bckg_color[i-1, j-1] = str(color_in_hex)

pd.DataFrame(bckg_color)

sf = StyleFrame.read_excel(excel_file, read_style=True, use_openpyxl_styles=False, header=None)
bckg_color = StyleFrame(sf.applymap(lambda cell: cell.style.bg_color)).data_df.astype(str)

bckg_color

这两种方法的结果是一样的:

我期望的结果是第四行的颜色应该是一样的,但实际上并不是,因为那一行有合并的单元格。有没有什么更好的方法(除了在颜色数据框上使用bfill)来获取颜色,以便整行都能显示我在截图中看到的颜色?我怀疑可以通过openpyxl获取合并单元格的信息来实现,但我不想这样做。

1 个回答

0

我觉得你无法避免在使用 openpyxl 时处理合并单元格。不过这其实很简单,只需要检查一下某个单元格是否属于一个合并的区域就可以了:

for i in range(1,rows+1):
    for j in range(1,cols+1):
        cell = None

        for mcl in sh.merged_cells:
            if mcl.min_row <= i <= mcl.max_row and mcl.min_col <= j <= mcl.max_col:
                cell = mcl.start_cell # that's where the background info is stored
                break

        if cell is None: cell = sh.cell(column=j, row=i)
        color_in_hex = cell.fill.start_color.index
        bckg_color[i-1, j-1] = str(color_in_hex)

撰写回答