简体   繁体   中英

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:

#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...

The file before writing:

在此输入图像描述

The file after writing:

在此输入图像描述

Any ideas are appreciated.

pandas does not do the column widths (or styling) for you. It does however provide the means to apply these yourself by accessing the 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:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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