使用Python编写文本包装的Excel文件 [英] Writing text wrapped Excel Files using Python

查看:118
本文介绍了使用Python编写文本包装的Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我正在通过处理一些CSV文件并从中制作一个excel文件进​​行练习.到目前为止,我可以获取excel文件,但是我无法通过python包装单元格.我已经尝试了多种方法,但是都没有用.也许是因为我对Python的了解不足.有人可以建议我在写excel文件时如何换行吗?并请一路解释代码?我为以下代码得到的错误是: 'str'对象没有属性'alignment'

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

推荐答案

您可以在xlsxwriter引擎(默认设置)中使用熊猫.

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

您需要通过调用xlsxwriter文档(链接这里).

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

使用pandas.DataFrame.to_excel()后,可以使用worksheet.set_column()添加格式.可以在xlsxwriter文档中找到一个示例(链接此处).

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

预期输出:

这篇关于使用Python编写文本包装的Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆