Python在Excel中设置样式和字体大小 [英] Python Setting Style and Font Size in Excel

查看:139
本文介绍了Python在Excel中设置样式和字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,请注意:我正在学习Python:

Here is my code, please note: am currently learning Python:

import openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
italic24Font = Font(size=24, italic=True)
sheet['A1'].font = italic24Font
sheet['A1'] = 'Hello world!'
wb.save('styled.xlsx')

这是我的错误消息:

Traceback (most recent call last):
  File "<pyshell#94>", line 1, in <module>
    sheet['A1'].font = italic24Font
AttributeError: can't set attribute

我不明白为什么我不能设置属性.我在做什么错了?

I don't understand why I can't set the attribute. What am I doing wrong?

编辑#1:

到目前为止我尝试过的是:使用 wb.get_sheet_names()检查工作表名称,并确保使用正确的名称.我实际上使用的是正确的名称.

What I have tried so far: using wb.get_sheet_names() to check the sheet name and make sure I'm using the correct name. I am in fact using the correct name.

编辑#2:

我尝试通过以下操作查看对象可用的方法:

I tried viewing the methods available to my object by doing the following:

dir(sheet['A1'].font)

我得到的结果是:

['UNDERLINE_DOUBLE', 'UNDERLINE_DOUBLE_ACCOUNTING', 'UNDERLINE_SINGLE', 'UNDERLINE_SINGLE_ACCOUNTING', '__add__', '__base__', '__class__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__fields__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__print__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__sub__', '__subclasshook__', '__weakref__', '_key', '_make_key', 'b', 'bold', 'charset', 'color', 'condense', 'copy', 'extend', 'family', 'i', 'italic', 'name', 'outline', 'scheme', 'shadow', 'size', 'spec', 'strike', 'strikethrough', 'sz', 'u', 'underline', 'vertAlign']

我尝试运行此命令:

sheet['A1'].font.size=24

但是我收到此错误消息:

But I got this error message:

TypeError: cannot set size attribute

有趣.

编辑#3 :

print(sheet['A1'].style.font.size)
11.0

但是当我尝试:

sheet['A1'].style.font.size=11

我收到此错误消息:

无法设置尺寸属性

cannot set size attribute

推荐答案

我完全按照原样运行了代码.它执行时没有AttributeError或与此有关的任何其他错误.首先,检查您是否具有修改 Sheet 设置的正确权限.其次,检查您的 openpyxl 软件包是否已更新为当前版本(也许旧版本中的语法可能有所不同).

I ran your code exactly as it is. It executed without the AttributeError or any other error for that matter. First, check if you have the right permissions for modifying the settings of Sheet. Second, check that your openpyxl package is updated to the current version (perhaps the syntax in the older versions may have been different).

通常,当您尝试为无法设置的属性/属性设置值时会引发AttributeError.

In general, AttributeError is raised when you are trying to set a value to an attribute/property that cannot be set because it does not have a setter.

这篇关于Python在Excel中设置样式和字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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