Trouble with applying Styles in - OpenPyXL

為{幸葍}努か 提交于 2019-12-22 08:18:06

问题


I am trying to style specific rows and columns.

worksheet.cell(row=file_row_number, column=1).value = "Hotel ID"
_cell = worksheet.cell("C1")
_cell.style.font.bold = True

It shows me error

TypeError: cannot set bold attribute

Previously I was using XLWT and it had very easy method of applying styles like you define style variable once and then for ever write() yo can just pass the style variable to apply style on that row/column

Is there any way in OpenPyXL to apply style easily as I mentioned above?


回答1:


As explained here, you should first create a Style object:

from openpyxl.styles import Style, Font

s = Style(font=Font(bold=True))

Then you can apply it to your cell like this:

_cell.style = s



回答2:


This has changed since the accepted answer was given.

If you do what the accepted answer suggests, you will receive this warning: UserWarning: Use formatting objects such as font directly warn("Use formatting objects such as font directly")

The answer still works but the new solution would be to apply it to the cell directly, for example: worksheet.cell("C1").font = Font(bold=True)



来源:https://stackoverflow.com/questions/26954788/trouble-with-applying-styles-in-openpyxl

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