【问题标题】:Format Excel Column header for better visibility and Color格式化 Excel 列标题以获得更好的可见性和颜色
【发布时间】:2018-11-12 20:38:07
【问题描述】:

我浏览了很多帖子,但没有找到执行以下操作的确切方法。 很抱歉附上截图(只是为了更好的可见性),我也会写的。 基本上它看起来像 -

Name_of_the_Man Address_of_Man  City
Jordan           NC             LMN

输入 csv 看起来像

需要输出

我有这段代码,可以选择 csv 并在 excel 中作为工作表附加。

writer = pd.ExcelWriter('final.xlsx'), engine='xlsxwriter')
for f in glob.glob(os.path.join(Path, "*.csv")):
         df = pd.read_csv(f)
         df.to_excel(writer, sheet_name=os.path.basename(f))
writer.save()

我想要我的 csv 文件 - 中间有足够的空间并为列标题着色。我已经浏览了这个链接 Python - change header color of dataframe and save it to excel file 但它没有达到目的 - 它正在为除了列之外的工作表本身着色。

更新: 得到了下面的答案。还想知道这是否可能只是一个想法

【问题讨论】:

标签: python excel python-3.x pandas csv


【解决方案1】:

您可以使用Pandas Excel output with user defined header formatsolution 来按内容更改宽度:

writer = pd.ExcelWriter("file.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object. Note that we turn off
# the default header and skip one row to allow us to insert a user defined
# header. Also remove index values by index=False
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'fg_color': '#ffcccc',
    'border': 1})
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num, value, header_format)

    column_len = df[value].astype(str).str.len().max()
    # Setting the length if the column header is larger
    # than the max column value length
    column_len = max(column_len, len(value)) + 3
    print(column_len)
    # set the column length
    worksheet.set_column(col_num, col_num, column_len)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

改变了你的解决方案:

writer = pd.ExcelWriter('final.xlsx'), engine='xlsxwriter')
for f in glob.glob(os.path.join(Path, "*.csv")):
         df = pd.read_csv(f)
         df.to_excel(writer, sheet_name=os.path.basename(f))

        workbook  = writer.book
        worksheet = writer.sheets[os.path.basename(f)]
        # Add a header format.
        header_format = workbook.add_format({
            'bold': True,
            'fg_color': '#ffcccc',
            'border': 1})
        for col_num, value in enumerate(df.columns.values):
            worksheet.write(0, col_num, value, header_format)
            column_len = df[value].astype(str).str.len().max()
            # Setting the length if the column header is larger
            # than the max column value length
            column_len = max(column_len, len(value)) + 3
            print(column_len)
            # set the column length
            worksheet.set_column(col_num, col_num, column_len)

writer.save()

编辑:

writer = pd.ExcelWriter("file.xlsx", engine='xlsxwriter')

#skip 2 rows
df.to_excel(writer, sheet_name='Sheet1', startrow=2, header=False, index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'fg_color': '#ffcccc',
    'border': 1})

#create dictionary for map length of columns 
d = dict(zip(range(25), list(string.ascii_uppercase)))
#print (d)

max_len = d[len(df.columns) - 1]
print (max_len)
#C
#dynamically set merged columns in first row
worksheet.merge_range('A1:' + max_len + '1', 'This Sheet is for Personal Details')

for col_num, value in enumerate(df.columns.values):
    #write to second row
    worksheet.write(1, col_num, value, header_format)

    column_len = df[value].astype(str).str.len().max()
    column_len = max(column_len, len(value)) + 3
    worksheet.set_column(col_num, col_num, column_len)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

【讨论】:

  • 是的,它工作正常。我在想我们是否可以在列标题上方添加一些粗体文本,例如,;'This Sheet is for this thing'?并从第二行放入 csv,只是一个想法?
  • @RishuA - 给我一些时间,第一行需要 colspan 吗?
  • 感谢您放置这些 cmets 。我正在用 pandas 学习 excel,这些都是有用的东西?
  • 我只在最后一段中删除它,以便与之前的差异容易:) 当然,最好不要删除原始 cmets。
  • 感谢您的链接。现在要去读书了。今天非常感谢。
猜你喜欢
  • 2019-12-23
  • 1970-01-01
  • 2019-09-19
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多