xlsxwriter-根据列名定义列格式

时间:2018-11-22 10:38:26

标签: python xlsxwriter

如何在xlsxwriter中基于列名定义列的表单。

例如,当列名称为 Sale_Date 时,我想定义 date_format ,而如果列名称为 count_of_sales ,我想使用< em> number_format

我知道如何为特定列定义格式,但是我不确定如何根据列名定义格式,如下所示。

date_format = workbook.add_format({'num_format': 'dd/mm/yyyy hh:mm:ss', 'font_size': 14})
worksheet1.write('A1', 'Sale_Date', date_format) 

任何人都可以提出建议。谢谢。

更新:

# create an output stream
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')

# Create the workbook
workbook = writer.book
# Create and name the sheets
worksheet = workbook.add_worksheet('Cover Sheet')
worksheet1 = workbook.add_worksheet('Sample Data')

# Number formatting
number_format = workbook.add_format({'num_format': '####', 'font_size': 14})
date_format = workbook.add_format({'num_format': 'dd/mm/yyyy hh:mm:ss', 'font_size': 14})

for col in field_names:
    worksheet1.write('A1', col, date_format if 'created_at' in col else number_format)

# Defining Cover sheet format
worksheet.set_column('A:BZ', None, color_format)

# # header column
row = 0
col = 0

for data in title:
    worksheet1.write(row, col, data, number_format)
    col += 1

#Pulling monthly data for columns for weekly raw data sheet
current_row = 1

for values in output_file:
    for idx, value in enumerate(values):
        worksheet1.write(current_row, idx, value, number_format)
    current_row += 1

# the writer has done its job
writer.close()

# go back to the beginning of the stream
output.seek(0)

# finally return the file
return output

示例列列表:

name, age,class,join_date,date_of_birth,filing_date

0 个答案:

没有答案