简体   繁体   English

如何使用 openpyxl 读取工作表的标签颜色

[英]How to read the tab color of a worksheet with openpyxl

I have been writing a script using the openpyxl module for python 3.8.3.我一直在为 python 3.8.3 使用 openpyxl 模块编写脚本。 In my script I am taking a pre-existing excel workbook with multiple sheets.在我的脚本中,我使用了一个预先存在的 excel 工作簿,其中包含多张工作表。 This sheet is coming from another person, and they want me to only run the script on the tabs that are colored with a specific color.此工作表来自另一个人,他们希望我只在以特定颜色着色的选项卡上运行脚本。 I have been attempting to recognize what worksheets have the specified color by using the tabColor in sheet_properties, but that does not work for me.我一直在尝试通过使用 sheet_properties 中的 tabColor 来识别哪些工作表具有指定的颜色,但这对我不起作用。 Any help is appreciated!任何帮助表示赞赏! Here这里

def excel_modifications(file_path, storage_path):
    initial_wb = load_workbook(file_path, data_only=True, read_only=True)
    for ws in initial_wb:
      if ws.sheet_properties.tabColor == "11217371":
          common_compression(ws, storage_path)

To anyone who is encountering a similar problem to me I found my solution.对于遇到与我类似问题的任何人,我都找到了解决方案。 The parameters within which is used by sheet_properties.tabColor contain both a 'rgb' parameter and a 'theme' parameter. sheet_properties.tabColor 使用的参数包含“rgb”参数和“主题”参数。 In my case, the workbook tabs from the work book I worked on were colored by theme colors, not a rgb value chosen by the person writing the excel sheet.在我的例子中,我处理的工作簿中的工作簿选项卡由主题 colors 着色,而不是编写 excel 表的人选择的 rgb 值。 On my workbook, the writer colored their tab with the Accent 6 in the default theme colors.在我的工作簿上,作者使用默认主题 colors 中的 Accent 6 为他们的标签着色。 So for me, the solution was to look for the index of the given sheet_properties.tabColor.theme that is equal to 6, as by starting from zero, the color I was searching for was the 9th index on the list provided by excel.所以对我来说,解决方案是寻找等于 6 的给定 sheet_properties.tabColor.theme 的索引,因为从零开始,我正在搜索的颜色是 excel 提供的列表中的第 9 个索引。

Here is my working conditional fixing my problem above:这是我解决上述问题的工作条件:

def excel_modifications(file_path, storage_path):
    initial_wb = load_workbook(file_path, data_only=True, read_only=True)
      for ws in initial_wb:
        if ws.sheet_properties.tabColor.theme == 6:
          common_compression(ws, storage_path)

Here is a screenshot from the listing discussed of Accents in excel: Example Accent listing from excel这是 excel 中讨论的口音列表的屏幕截图: excel 中的示例口音列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM