Writing text wrapped Excel Files using Python

安稳与你 提交于 2019-12-14 03:51:24

问题


I am new to Python and I was practicing by processing some CSV files and making an excel file from them. So far I can get the excel file however, I am unable to wrap the cells via python. I have tried multiple ways but none of it would work. Perhaps it is because of my poor understanding of Python. Can anyone suggest me how can I wrap text while writing the excel file? And please explain the code along the way? The error that i am getting for the following code is: 'str' object has no attribute 'alignment'

This is what I have done so far:

df=pd.DataFrame(list(zip(Dticketnumberlist,Dcategorylist)), 
             columns=['Ticket', 'Category'])

writer = pd.ExcelWriter('Trial Version.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook=writer.book
worksheet = writer.sheets['Sheet1']

wrap_alignment = Alignment(wrap_text=True)
cell.alignment = wrap_alignment

回答1:


You can use pandas with the xlsxwriter engine (the default).

You need to create a format object by calling the workbook.add_format() method as outlined in the xlsxwriter docs (link here).

Once you've used pandas.DataFrame.to_excel(), you can add the format using worksheet.set_column(). An example of this can be found in the xlsxwriter docs (link here).

I've provided a fully reproducible example below with the expected output.

import pandas as pd

df = pd.DataFrame({'Ticket': ['a','b','c','d'],
                  'Category': [2,1,4,3]})


writer = pd.ExcelWriter('Trial Version.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook=writer.book
worksheet = writer.sheets['Sheet1']

format = workbook.add_format({'text_wrap': True})

# Setting the format but not setting the column width.
worksheet.set_column('A:B', None, format)

writer.save()

Expected Output:




回答2:


Use python xlsxwriter

The question answered previously can help you better.



来源:https://stackoverflow.com/questions/51631138/writing-text-wrapped-excel-files-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!