【问题标题】:Trouble with applying Styles in - OpenPyXL在 OpenPyXL 中应用样式时遇到问题
【发布时间】:2014-11-16 07:20:28
【问题描述】:

我正在尝试设置特定行和列的样式。

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

显示错误

TypeError: cannot set bold attribute

以前我使用XLWT,它有非常简单的方法来应用样式,比如你定义style变量一次然后永远write()你可以传递style变量来在该行上应用样式/专栏

OpenPyXL 有什么方法可以像我上面提到的那样轻松应用样式吗?

【问题讨论】:

    标签: python python-3.x openpyxl


    【解决方案1】:

    自从给出接受的答案后,情况发生了变化。

    如果您按照公认答案的建议进行操作,您将收到以下警告: UserWarning:直接使用字体等格式化对象 warn("直接使用字体等格式化对象")

    答案仍然有效,但新的解决方案是将其直接应用于单元格,例如: worksheet.cell("C1").font = Font(bold=True)

    【讨论】:

    • 如果你想遍历一系列单元格,这里有一个例子:for row in worksheet.iter_rows('A1:L1'): for cell in row: cell.number_format = '0' cell.font = Font(bold=True)
    【解决方案2】:

    正如here 解释的那样,您应该首先创建一个Style 对象:

    from openpyxl.styles import Style, Font
    
    s = Style(font=Font(bold=True))
    

    然后你可以像这样将它应用到你的单元格:

    _cell.style = s
    

    【讨论】:

    • 知道了……我还有一个困惑……我可以写一个值并在一行中应用一个样式吗?就像我下面的评论...我在 2 行中写值和应用样式...可以在 1 行中完成吗?
    • worksheet.cell(row=file_row_number, column=1).value = "Hotel ID" # 应用风格 worksheet.cell(row=file_row_number, column=1).style = Style(font=Font(bold=True))
    • 据我所知,您需要两条指令来更改值和应用样式。您不能在 1 行中同时执行这两项操作。
    • 如何设置列宽?
    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2014-10-27
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多