简体   繁体   English

在Python中编写excel文件,.xlsx格式

[英]Writing excel files, the .xlsx format in Python

I'm starting with a big data frame which after some data mining work I need to reduce it to a file with 2 sheets and writing the file after... This question refers to the writing part and more exactly if I use: 我从一个大数据框架开始,经过一些数据挖掘工作,我需要将它减少到一个2张文件,然后写入文件......这个问题涉及写作部分,更确切地说,如果我使用:

#write the files:

# first file:
# Specify a writer
writer = pd.ExcelWriter('example1.xlsx', engine='xlsxwriter')

# Write your DataFrame to a file     
df11.to_excel(writer, 'Sheet1')
df12.to_excel(writer, 'Sheet2')
# Save the result 
writer.save()

I get the same dimension allocated for all the columns, even if they are formed from numbers or text. 我获得了为所有列分配的相同维度,即使它们是由数字或文本组成的。 And for some reason I get an another column with the row nr from the previous file, despite the fact that if I visualize the files in Rodeo looks just fine... 由于某种原因,我得到了另一个列,其中包含来自前一个文件的行nr,尽管如果我在Rodeo中可视化文件看起来很好......

The file before writing: 写入前的文件:

在此输入图像描述

The file after writing: 写完后的文件:

在此输入图像描述

Any ideas are appreciated. 任何想法都表示赞赏。

pandas does not do the column widths (or styling) for you. pandas不会为您执行列宽(或样式)。 It does however provide the means to apply these yourself by accessing the xlsxwriter . 但它提供了通过访问xlsxwriter来自行应用这些方法的方法 To set the width of a column you can do: 要设置列的宽度,您可以执行以下操作:

Code: 码:

# make wide column wide
workbook = writer.book
worksheet = workbook.worksheets()[1]
worksheet.set_column('B:B', 24)

Test Code: 测试代码:

# Specify a writer
writer = pd.ExcelWriter('example1.xlsx', engine='xlsxwriter')

df1 = pd.DataFrame([1], columns=['A'])
df2 = pd.DataFrame(['My data'], columns=['This is a very wide column'])

# Write your DataFrame to a file
df1.to_excel(writer, 'Sheet1')
df2.to_excel(writer, 'Sheet2')

# make wide column wide
workbook = writer.book
worksheet = workbook.worksheets()[1]
worksheet.set_column('B:B', 24)

# Save the result
writer.save()

Results: 结果:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM