简体   繁体   中英

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. In my script I am taking a pre-existing excel workbook with multiple sheets. 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. 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. 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. On my workbook, the writer colored their tab with the Accent 6 in the default theme colors. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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