Python XLSXWriter。列的header_format子特制参数无法按预期工作

发布于 2025-02-13 03:52:13 字数 2237 浏览 2 评论 0原文

我需要在下一个日期格式中以Excel设置一个表标头:'Mmm-yy'。 格式化我已经设置了:

title_date_format = workbook.add_format({
    'text_wrap': True,
    'font_size': 11,
    'num_format': 'mmm-yy'
})

列设置:

column_settings = []
index = 0
for column in df.columns:    
    if index < 3:
        dct = {}
        dct['header'] = column
        column_settings.append(dct)       
    else:
        dct = {}                
        formula = '=[@[Value]]*[@Qty]'      
        dct['header'] = column
        dct['formula'] = formula
        dct['header_format'] = title_date_format
        column_settings.append(dct)
    index += 1

表创建:

# Create a table
worksheet.add_table(0, 0, max_row + 2, max_col - 1, {
     'columns': column_settings
})

问题是只有'text_wrap'和font_size'子专业工作正常。列标题是日期,以“ 1/24/2022”格式而不是'jan-22',所以'num_format':'mmm-yy'不适用。

完整的例子:

import datetime as dt
import pandas as pd
import numpy as np
import xlsxwriter

initial_data = {
    'Category': ['catA', 'catB', 'catC', 'catC'],
    'Item': ['item1', 'item2', 'item3', 'item4']
}
df = pd.DataFrame(initial_data)
# Add columns with month-year
for year in range(2,4):
    if year == 2:
        for month in range(11,13):
            date_str = str(month) + '/1/202' + str(year)
            df[date_str] = ''
    else:
        for month in range(1,4):
            date_str = str(month) + '/1/202' + str(year)
            df[date_str] = ''

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', header=False, startrow=1, index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

title_date_format = workbook.add_format({
        'text_wrap': True,
        'font_name': 'Calibri',
        'font_size': 10,
        'num_format': 'mmm-yy'
    })
column_settings = []
for column in df.columns:    
    dct = {}
    dct['header'] = column
    dct['header_format'] = title_date_format
    column_settings.append(dct)

(max_row, max_col) = df.shape
worksheet.add_table(0, 0, max_row, max_col - 1, {
        'columns': column_settings, 
        'style': 'Table Style Light 9'
    })
writer.save()

关于如何使其工作的任何想法?

谢谢

I need to set a table header in Excel with the next date format: 'mmm-yy'.
Formatting I've set:

title_date_format = workbook.add_format({
    'text_wrap': True,
    'font_size': 11,
    'num_format': 'mmm-yy'
})

Column settings:

column_settings = []
index = 0
for column in df.columns:    
    if index < 3:
        dct = {}
        dct['header'] = column
        column_settings.append(dct)       
    else:
        dct = {}                
        formula = '=[@[Value]]*[@Qty]'      
        dct['header'] = column
        dct['formula'] = formula
        dct['header_format'] = title_date_format
        column_settings.append(dct)
    index += 1

Table creation:

# Create a table
worksheet.add_table(0, 0, max_row + 2, max_col - 1, {
     'columns': column_settings
})

The problem is that only the 'text_wrap' and font_size' sub-properties work fine. The column header, which is a date, stays in '1/24/2022' format instead of 'Jan-22', so 'num_format': 'mmm-yy' doesn't apply.

Full example:

import datetime as dt
import pandas as pd
import numpy as np
import xlsxwriter

initial_data = {
    'Category': ['catA', 'catB', 'catC', 'catC'],
    'Item': ['item1', 'item2', 'item3', 'item4']
}
df = pd.DataFrame(initial_data)
# Add columns with month-year
for year in range(2,4):
    if year == 2:
        for month in range(11,13):
            date_str = str(month) + '/1/202' + str(year)
            df[date_str] = ''
    else:
        for month in range(1,4):
            date_str = str(month) + '/1/202' + str(year)
            df[date_str] = ''

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', header=False, startrow=1, index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

title_date_format = workbook.add_format({
        'text_wrap': True,
        'font_name': 'Calibri',
        'font_size': 10,
        'num_format': 'mmm-yy'
    })
column_settings = []
for column in df.columns:    
    dct = {}
    dct['header'] = column
    dct['header_format'] = title_date_format
    column_settings.append(dct)

(max_row, max_col) = df.shape
worksheet.add_table(0, 0, max_row, max_col - 1, {
        'columns': column_settings, 
        'style': 'Table Style Light 9'
    })
writer.save()

Any ideas on how to make it work?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不离久伴 2025-02-20 03:52:13

问题是列标题是字符串,日期编号格式仅适用于数字。因此,解决方案是将列标题转换为DateTime号码,以便可以应用格式。但是,据我所知,Excel中的表列标题需要是字符串,因此这不是一个选择。

因此,作为解决方法,您可以格式化当前正在使用的标题字符串:

# ...
from datetime import datetime

# ...

for year in range(2,4):
    if year == 2:
        for month in range(11,13):
            date_str = datetime(2022, month, 1).strftime("%b-%y")
            df[date_str] = ''
    else:
        for month in range(1,4):
            date_str = datetime(2024, month, 1).strftime("%b-%y")
            df[date_str] = ''

输出:

“输入图像描述在这里”

The issue is that the column headers are strings and the date number format only applies to numbers. So the solution would be to turn the column headers into datetime numbers so that the format can be applied. However, as far as I can see Table column headers in Excel need to be strings, so that isn't an option.

So as a workaround you could format the header strings that you are currently using into the format that you want:

# ...
from datetime import datetime

# ...

for year in range(2,4):
    if year == 2:
        for month in range(11,13):
            date_str = datetime(2022, month, 1).strftime("%b-%y")
            df[date_str] = ''
    else:
        for month in range(1,4):
            date_str = datetime(2024, month, 1).strftime("%b-%y")
            df[date_str] = ''

Output:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文