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

标签 python dataframe formatting xls

我想首先展示一个适用于 XLSX 的示例(但不幸的是我需要 XLS 并且此方法不适用于该情况)。再次澄清一下,我的主要问题是生成的 XLS 文件的列类型格式

# 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:\users\3619678\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:\users\3619678\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:\users\3619678\desktop\example_file.xls')

但是这个版本的问题是它不仅不显示标题,而且还将格式应用于所有单元格。如果有人能帮助我,我将非常感激,我已经在这上面花了很多时间了!

最佳答案

使用 df.to_excel 应该容易得多

df.to_excel('c:\users\3619678\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 文档,可能没有您想要使用的工具。因此,我添加了标题和一种按列格式化的简单方法

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')

关于python - 如何将 Python Pandas DataFrame 写入具有特定列类型格式的 .XLS 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60121880/

相关文章:

python - 在 python 中解析文本的最佳工具是什么?

python - Pandas pytables 追加 : performance and increase in file size

pandas - 如何读取包含许多 CSV 文件的许多大型 .7z 文件?

python - 使用 matplotlib 更新灰度图像

java - 使用 python-javaobj 在纯 python 中实现 java 反序列化?

Python循环两个不同的数据帧来创建一个新列

python - 如何使用 Python 在一个命令中追加和设置值?

database - PostgreSql:获取格式奇怪的 "timestamp with time zone"

java - 防止 Int 将 012345 更改为 5349

C段错误,不确定发生了什么