如何将 Python Pandas DataFrame 写入具有特定列类型格式的 .XLS 文件?

How to write a Python Pandas DataFrame to an .XLS file with specific column type formatting?

我想首先展示一个适用于 XLSX 的示例(但遗憾的是我需要 XLS,而此方法不适用于此)。 re-clarify,我的主要问题是生成的 XLS 文件的 column-type 格式

# Method that works for XLSX
import pandas as pd

# Example Dataframe
df = pd.DataFrame({'Numbers': [1000, 2000, 3000, 4000, 5000],
                   'Names': ['Adam','Blake','Chad','Drake','Erak'],
                   'Weights': [1.05, 2.10, 3.15, 4.20, 5.25],
})

# Create a Pandas Excel writer
writer = pd.ExcelWriter(r'c:\users19678\desktop\example_file.xlsx')

# Convert the dataframe to an Excel object
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Get the xlsxwriter workbook and worksheet objects
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Define cell formats
number_format = workbook.add_format({'num_format': '0.00'})

# Set a certain column's width and apply certain format
worksheet.set_column('A:A', 20, number_format)

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

现在这是我迄今为止对 XLS 版本最接近的尝试:

import pandas as pd

# Example Dataframe
df = pd.DataFrame({'Numbers': [1000, 2000, 3000, 4000, 5000],
                   'Names': ['Adam','Blake','Chad','Drake','Erak'],
                   'Weights': [1.05, 2.10, 3.15, 4.20, 5.25],
})

import xlwt

# Create a workbook and add a worksheet
workbook = xlwt.Workbook(r'c:\users19678\desktop\example_file.xls')
worksheet = workbook.add_sheet('sheet1',cell_overwrite_ok=True)

# Create formats
number_format = xlwt.easyxf(num_format_str='0.00')

# Iterate over the data and write it out row by row
for x, y in df.iterrows():
    for z, value in enumerate(y):
        worksheet.write(x, z, value, number_format)

# Save/output the workbook
workbook.save(r'c:\users19678\desktop\example_file.xls')

然而,此版本的问题在于它不仅不显示 headers,还将格式应用于所有单元格。如果有人能帮助我,我将不胜感激,我为此付出了永远!

使用 df.to_excel 应该容易得多

df.to_excel('c:\users19678\desktop\example_file.xls', sheet_name='sheet1', float_format = "%.2f")

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html

[编辑] 看起来这可能还不够好。根据 xlwt 文档,可能没有您想要使用的工具。因此,我添加了 headers 和一种按列格式化的简单方法

import pandas as pd

# Example Dataframe
df = pd.DataFrame({'Numbers': [1000, 2000, 3000, 4000, 5000],
                   'Names': ['Adam','Blake','Chad','Drake','Erak'],
                   'Weights': [1.05, 2.10, 3.15, 4.20, 5.25],
})

import xlwt

# Create a workbook and add a worksheet
workbook = xlwt.Workbook('example_file.xls')
worksheet = workbook.add_sheet('sheet1',cell_overwrite_ok=True)

# Create dictionary of formats for each column
number_format = xlwt.easyxf(num_format_str='0.00')
cols_to_format = {0:number_format}

for z, value in enumerate(df.columns):
    worksheet.write(0, z, value)

# Iterate over the data and write it out row by row
for x, y in df.iterrows():
    for z, value in enumerate(y):
        if z in cols_to_format.keys():
            worksheet.write(x + 1, z, value, cols_to_format[z])
        else: ## Save with no format
             worksheet.write(x + 1, z, value)

# Save/output the workbook
workbook.save('example_file.xls')