openpyxl 設置單元格顏色


在處理excel數據格式的時候,需要對特定單元格進行顏色標注,方便相關人員查看 醒目

# -*- coding: utf-8 -*-

from openpyxl import load_workbook, Workbook
# 導入字體、邊框、顏色以及對齊方式相關庫
from openpyxl.styles import Font, Border, Side, PatternFill, colors, Alignment

有關顏色的設置具體可以查看  http://www.114la.com/other/rgb.htm

def MarkRedOverTime():
    '''對上周已開船和未開船 超時數據字段進行標紅'''
    try:
        abs_file = os.path.abspath(os.path.join(
            os.path.dirname(__file__), outfile))
        wb = load_workbook(abs_file)
        # 獲取工作表列表
        sheets = wb.sheetnames
        print(sheets)
        # 獲取某一特定的工作表
        # 上一周新增的可發訂單已開船數據  上一周新增的可發訂單未開船數據
        #
        # 上一周新增的可發訂單已開船數據ws = wb["上一周新增的可發訂單未開船數據"]

        # # 設置填充紅色加粗
        red_fill = PatternFill("solid", fgColor="FF0000")
        # # 遍歷每一行
        # for index, row in enumerate(ws.rows):
        #     if index > 0:
        #         # 單證工作時間(時) > 24
        #         cell6 = row[5]
        #         print(cell6.value)
        #         if int(cell6.value) > 24:
        #             cell6.fill = red_fill
        #         # 采購工作時間(時) > 48
        #         cell9 = row[8]
        #         if int(cell9.value) > 48:
        #             cell9.fill = red_fill
        #         # 訂艙用時(時) > 48
        #         cell12 = row[11]
        #         if int(cell12.value) > 48:
        #             cell12.fill = red_fill
        #         # booking是否超時(天) < 0
        #         cell14 = row[13]
        #         if int(cell14.value) < 0:
        #             cell14.fill = red_fill
        wt = wb["上一周新增的可發訂單已開船數據"]
        # 遍歷每一行
        for index, row in enumerate(wt.rows):
            if index > 0:
                # 單證工作時間(時) > 24
                cell6 = row[5]
                if int(cell6.value if cell6.value else "0") > 24:
                    cell6.fill = red_fill
                # 采購工作時間(時) > 48
                cell9 = row[8]
                if int(cell9.value if cell9.value else "0") > 48:
                    cell9.fill = red_fill
                # 訂艙用時(時) > 48
                cell12 = row[11]
                if int(cell12.value if cell12.value else "0") > 48:
                    cell12.fill = red_fill
                # booking是否超時(天) < 0
                cell14 = row[13]
                if int(cell14.value if cell14.value else "0") < 0:
                    cell14.fill = red_fill
                # shipping是否超時(天) < 0
                cell18 = row[17]
                if int(cell18.value if cell18.value else "0") < 0:
                    cell18.fill = red_fill
        wb.save(abs_file)
    except Exception as error_msg:
        print(error_msg)
        fs = traceback.format_exc()
        print(fs)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM