设置Python中Excel文件的所有工作表的标题颜色和边框。

huangapple go评论65阅读模式
英文:

Set Header colour and border for all sheets in an excel file with python

问题

我有一个包含多个工作表的Excel文件。我尝试一次性设置所有Excel工作表的标题背景颜色和边框。

这些Excel工作表是我通过ExcelWriter创建的输出数据框架。

writer = pd.ExcelWriter(os.path.join(path, 'file.xlsx'), engine='xlsxwriter')
df1.to_excel(writer, sheet_name='df1', index=False)
df2.to_excel(writer, sheet_name='df2', index=False)
# 以此类推

我只是试图找出如何在这些工作表中添加格式。

英文:

I have an Excel file with multiple sheets. I am trying to set the header background colour and border for all the Excel sheets at once.

This excel sheets are output dataframes which I am creating through ExcelWriter.

writer = pd.ExcelWriter(os.path.join(path, 'file.xlsx'), engine = 'xlsxwriter'
df1.to_excel(writer, sheetname = 'df1', index = False)
df2.to_excel(writer, sheetname = 'df2', index = False)
.
.
.
.
and so on

I'm just trying to figure out how to add the formatting in these sheets.

答案1

得分: 1

You can use add_format along with write to format cells in Excel using the xlsxwriter library. Here's the code you provided:

import pandas as pd
import xlsxwriter

dmap = {"bg_color": "#00D100", "border": 2, "bold": True}

df1 = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df2 = pd.DataFrame({"C": [7, 8], "D": [9, 10], "E": [11, 12]})

list_dfs = [df1, df2]

with pd.ExcelWriter("output.xlsx", engine="xlsxwriter") as writer:
    for idx1, df in enumerate(list_dfs, start=1):
        ws_name = f"Sheet{idx1}" # change the sheet name here (df for example)
        df.to_excel(writer, sheet_name=ws_name, index=False)
        for idx2, col in enumerate(df.columns):
            writer.sheets[ws_name].write(0, idx2, col, writer.book.add_format(dmap))

Output:

设置Python中Excel文件的所有工作表的标题颜色和边框。

设置Python中Excel文件的所有工作表的标题颜色和边框。

英文:

IIUC, you can use add_format along with write :

import pandas as pd
import xlsxwriter

dmap = {"bg_color": "#00D100", "border": 2, "bold": True}

df1 = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df2 = pd.DataFrame({"C": [7, 8], "D": [9, 10], "E": [11, 12]})

list_dfs = [df1, df2]

with pd.ExcelWriter("output.xlsx", engine="xlsxwriter") as writer:
    for idx1, df in enumerate(list_dfs, start=1):
        ws_name = f"Sheet{idx1}" # change the sheet name here (df for example)
        df.to_excel(writer, sheet_name=ws_name, index=False)
        for idx2, col in enumerate(df.columns):
            writer.sheets[ws_name].write(0, idx2, col, writer.book.add_format(dmap))

Output :

设置Python中Excel文件的所有工作表的标题颜色和边框。

设置Python中Excel文件的所有工作表的标题颜色和边框。

huangapple
  • 本文由 发表于 2023年4月17日 14:07:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定