繁体   English   中英

如何用Python填充excel行的背景颜色?

[英]How to fill background color of excel rows with Python?

我是 Python 的初学者。

  1. 我有一个excel文件。

     | Name | Reg Date | |Annie | 2021-07-01 | |Billy | 2021-07-02 | |Cat | 2021-07-03 | |David | 2021-07-04 | |Eric | 2021-07-04 | |Annie | 2021-07-01 | |Bob | 2021-07-05 | |David | 2021-07-04 |
  2. 我在excel中发现了重复的行。

    代码:

     import openpyxl as xl import pandas as pd import numpy as np dt = pd.read_excel('C:/Users/Desktop/Student.xlsx') dt['Duplicate'] = dt.duplicated() DuplicateRows=[dt.duplicated(['Name', 'Reg Date'], keep=False)] print(DuplicateRows)

    输出:

     Name Reg Date Duplicate 1 Annie 2021-07-01 False 6 Annie 2021-07-01 True 4 David 2021-07-04 False 8 David 2021-07-04 True
  3. 上面我有两个问题...请教我。

    Q1:如何将Duplicate值从False更新为True

    Q2:当DuplicateTrue时,如何填充Student.xlsx中保存的行的背景颜色?

duplicated()函数本身无法交换 True 和 False。 您可以使用 NOT 运算符 ( ~ ) 来实现这一点。 此外,使用PatternFill为相关行着色并写入student.xlsx 请参考下面的代码。

代码

import pandas as pd
import numpy as np
from openpyxl.styles import PatternFill
from openpyxl import Workbook

dt = pd.read_excel("myinput.xlsx", sheet_name="Sheet1")
dt['Duplicate'] = dt.duplicated()
dt['Duplicate'] = ~dt[dt.duplicated(['Name', 'Reg Date'], keep=False)].Duplicate
dt['Duplicate'] = dt['Duplicate'].replace(np.nan, False)

print(dt)

wb = Workbook()
ws = wb.active

# Write heading
for i in range(0, dt.shape[1]):
    cell_ref = ws.cell(row=1, column=i+1)
    cell_ref.value = dt.columns[i-1]

#Write and colot data rows
for row in range(dt.shape[0]):
    for col in range(dt.shape[1]):
        print(row, col, dt.iat[row, col])
        ws.cell(row+2,col+1).value = str(dt.iat[row, col])
        if dt.iat[row, 2] == True:
            ws.cell(row+2,col+1).fill = PatternFill(start_color='FFD970', end_color='FFD970', fill_type="solid")  # change hex code to change color

wb.save('student.xlsx')

输出表

在此处输入图像描述

更新请求

嗨 - 请在下面找到更新的代码。 这将从Student.xlsx Sheet1 中读取数据,并使用更新后的彩色表更新 Sheet2。 如果没有该名称的工作表,它将出错。 如果 Sheet2 中的特定单元格中有数据,则该数据将被覆盖,而不是任何其他数据。 只写NameReg Date 写入 excel 表后,数据框dtDuplicate列也将被删除,并且仅包含其他两列。 希望这很清楚,并且是您正在寻找的...

import pandas as pd
import numpy as np
from openpyxl.styles import PatternFill
from openpyxl import load_workbook

dt = pd.read_excel("Student.xlsx", sheet_name="Sheet1")
dt['Duplicate'] = dt.duplicated()
dt['Duplicate'] = ~dt[dt.duplicated(['Name', 'Reg Date'], keep=False)].Duplicate
dt['Duplicate'] = dt['Duplicate'].replace(np.nan, False)

wb = load_workbook("Student.xlsx")
ws = wb['Sheet2']  # Make sure this sheet exists, else, it will give an error

#Write Heading
for i in range(0, dt.shape[1]-1):
    ws.cell(row = 1, column = i+1).value = dt.columns[i]

#Write Data
for row in range(dt.shape[0]):
    for col in range(dt.shape[1] - 1):
        print(row, col, dt.iat[row, col])
        ws.cell(row+2,col+1).value = str(dt.iat[row, col])
        if dt.iat[row, 2] == True:
            ws.cell(row+2,col+1).fill = PatternFill(start_color='FFD970', end_color='FFD970', fill_type="solid")  # used hex code for brown color

wb.save("Student.xlsx")

dt = dt.drop(['Duplicate'], axis=1, inplace=True) # Finally remove the column Duplicated, in case you want to use it
print(dt)

输出 Excel

在此处输入图像描述

暂无
暂无

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

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