Pandas更改单元格的行/列颜色背景

b0zn9rqh  于 2022-11-08  发布在  PyCharm
关注(0)|答案(2)|浏览(692)

我写了一个脚本,冻结包含列名称的第一行,但我想使背景为“红色”。我尝试使用样式,但它不工作。

我收到此错误

我只想更改第一行的颜色,如列名。列名为蓝色

kpbwa7wx

kpbwa7wx1#

正如我们所讨论的,您的用例实际上包括以下步骤。
1.读取具有一个工作表的多个xlsx文件
1.创建另一个xlsx文件,并将xlsx文件中的所有内容写入新xlsx文件中的不同图纸。
有两种方法可以实现这一点
1.使用xlsxwriter
您可以循环浏览每个工作表,并设定所需的列/栏格式。

from timestampdirectory import createdir
from xlsxwriter.utility import xl_rowcol_to_cell
import xlsxwriter
import pandas as pd
import time
import os
import pandas.io.formats.excel
pandas.io.formats.excel.ExcelFormatter.header_style = None

def svnanalysis():
    dest = createdir()
    dfSvnUsers              = pd.read_excel(os.path.join(dest, "SvnUsers.xlsx")).fillna("N/A")
    dfSvnGroupMembership    = pd.read_excel(os.path.join(dest, "SvnGroupMembership.xlsx")).fillna("N/A")
    dfSvnRepoGroupAccess    = pd.read_excel(os.path.join(dest, "SvnRepoGroupAccess.xlsx")).fillna("N/A")
    dfsvnReposSize          = pd.read_excel(os.path.join(dest, "svnReposSize.xlsx")).fillna("N/A")
    dfsvnRepoLastChangeDate = pd.read_excel(os.path.join(dest, "svnRepoLastChangeDate.xlsx")).fillna("N/A")
    dfUserDetails           = pd.read_excel(r"C:\Users\hpoddar\Desktop\Temp\Champs\CM_UsersDetails.xlsx").fillna("N/A")

    timestr = time.strftime("%Y-%m-%d-")
    xlwriter = pd.ExcelWriter(os.path.join(dest, f'{timestr}Usage-SvnAnalysis.xlsx'))

    dfUserDetails.to_excel(xlwriter, sheet_name='UserDetails', index=False)
    dfSvnUsers.to_excel(xlwriter, sheet_name='SvnUsers', index=False)
    dfSvnGroupMembership.to_excel(xlwriter, sheet_name='SvnGroupMembership', index=False)
    dfSvnRepoGroupAccess.to_excel(xlwriter, sheet_name='SvnRepoGroupAccess', index=False)
    dfsvnReposSize.to_excel(xlwriter, sheet_name='svnReposSize', index=False)
    dfsvnRepoLastChangeDate.to_excel(xlwriter, sheet_name='svnRepoLastChangeDate', index=False)

    for column in dfSvnUsers:
        column_width = max(dfSvnUsers[column].astype(str).map(len).max(), len(column))
        col_idx = dfSvnUsers.columns.get_loc(column)

        # Width of column `col_idx` set to column_width.
        xlwriter.sheets['SvnUsers'].set_column(col_idx, col_idx, column_width)
        xlwriter.sheets['UserDetails'].set_column(col_idx, col_idx, column_width)
        xlwriter.sheets['SvnGroupMembership'].set_column(col_idx, col_idx, column_width)
        xlwriter.sheets['SvnRepoGroupAccess'].set_column(col_idx, col_idx, column_width)
        xlwriter.sheets['svnReposSize'].set_column(col_idx, col_idx, column_width)
        xlwriter.sheets['svnRepoLastChangeDate'].set_column(col_idx, col_idx, column_width)

    workbook = xlwriter.book
    # fomrat the header row
    cell_format = workbook.add_format({'bg_color': 'yellow'})
    cell_format.set_bold()
    cell_format.set_font_color('red')
    cell_format.set_border(1)

    # for each sheet in Usage-SvnAnalysis
    for sheet_name in xlwriter.sheets:
        ws = xlwriter.sheets[sheet_name]
        ws.freeze_panes(1, 0) # Freeze the first row.

        ws.conditional_format('A1:{}1'.format(chr(65 + ws.dim_colmax)), {'type': 'no_blanks', 'format': cell_format})

    xlwriter.close()

    print("UsageSvnAnalysis.xlsx a fost exportat cu succes continand ca sheet toate xlsx anterioare")

svnanalysis()

1.使用openpyxl,您可以再次读取xlsx,浏览每个工作表并设置所需的单元格格式。

from openpyxl.styles import PatternFill, Border, Font, Side
from timestampdirectory import createdir
import openpyxl 
import time
import os

dest=createdir()
timestr = time.strftime("%Y-%m-%d-")

xls = openpyxl.load_workbook(os.path.join(dest, f'{timestr}Usage-SvnAnalysis.xlsx'))

# create styles

font_style = Font(bold=True)
thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
fill_cell = PatternFill(patternType='solid',fgColor='35FC03')

for sheet_name in xls.sheetnames:
    ws = xls[sheet_name]

    # apply style to first row first column
    ws.cell(row=1, column=1).font = font_style
    ws.cell(row=1, column=1).border = thin_border
    ws.cell(row=1, column=1).fill = fill_cell

    # to color the entire row
    # Enumerate the cells in the first row
    for cell in ws["1:1"]:
        cell.font = font_style
        cell.border = thin_border
        cell.fill = fill_cell

xls.save(os.path.join(dest, f'{timestr}Usage-SvnAnalysis.xlsx'))

输出量:

wrrgggsh

wrrgggsh2#

伙计们,我成功地在第一行第一列(0,0)上添加了颜色,但它在所有工作表上更改了该行和列的名称,并显示为“False”。我不知道如何解决该问题,以便在不更改名称的情况下为整个行1添加颜色

workbook = xlwriter.book
        cell_format = workbook.add_format({
            'bold': True,
            'fg_color': '#00FFFF',
            'border': 1})
        ws.write(0,0,False,cell_format)

相关问题