【问题标题】:Draw Borders Without Overriding Previous Borders in Openpyxl (Python)在 Openpyxl (Python) 中绘制边框而不覆盖以前的边框
【发布时间】:2021-02-04 17:48:56
【问题描述】:

我最近一直在为一个项目使用 openpyxl 3.0.6,并希望在 Excel 2016 中自动绘制和调整一些复杂表格的大小。一切都很顺利,直到我尝试勾勒出一系列单元格并且之前的边框被覆盖.我的问题与覆盖先前的边界有关。比如

import openpyxl

workbook = openpyxl.load_workbook("Borders Test.xlsx")
sheet = workbook.active
cell = sheet["B6"]

border = openpyxl.styles.borders.Side(style = "thick")

# Draw a border on top of cell B6 #
cell.border = openpyxl.styles.Border(top = border)

# Draw a border on the bottom of cell B6, overwrites the above border #
cell.border = openpyxl.styles.Border(bottom = border)
workbook.save("Borders Test.xlsx")
workbook.close()

只会在'B6'的底部设置一个边框,因为这是最后一个,但我想要的输出是单元格B6,顶部和底部都有边框。请注意,在围绕范围绘制边框的情况下,我们可以在外侧绘制边框,因此我们可以通过将 B5 的下边框和 B7 的上边框设置为粗来获得所需的结果,但这并没有解决覆盖问题问题。我也试过这样修改'cell.border'

cell.border.left = openpyxl.styles.Border(left = border)

但我收到了错误消息:

'AttributeError: 样式对象是不可变的,不能改变。 用副本重新分配样式'

虽然这是一个选项,但它有点糟糕,我想看看是否有更好的方法。

如果这很重要,我在 Windows 10 和 python 3.7.8 中使用 64 位 python。

提前感谢您的帮助,希望我的第一篇文章不会太糟糕!

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    应同时对边界进行两项更改。 Border 可以取一个元组,这样就避免了设置边框然后覆盖它。

    代替:

    # Draw a border on top of cell B6 #
    cell.border = openpyxl.styles.Border(top = border)
    
    # Draw a border on the bottom of cell B6, overwrites the above border #
    cell.border = openpyxl.styles.Border(bottom = border)
    

    替换为:

    cell.border = openpyxl.styles.Border(top = border, bottom = border)
    

    【讨论】:

      【解决方案2】:

      虽然 Alan 说这可以完成是正确的,但我的目标(我表达得不好)是能够在第一次分配后返回并进行编辑,而不会丢失以前的边界。这是我提出的一个丑陋的解决方案:

      __elements__ = ('left', 'right', 'top', 'bottom')
      def drawSafely(cell, __side = Thick_side, _where = "left"):
         ### Overwrites only the value at _where
         kwargs = {element:getattr(cell.border,element) for element in __elements__}
         kwargs[_where] = __side
         border = openpyxl.styles.Border(**kwargs)
         cell.border = border
      

      其中单元格与问题陈述中的一样,“Thick_side”的类型为“openpyxl.styles.borders.Sid​​e”。这只是将旧数据保存在字典中,更新字典,重新制作边框,并将该值分配给 cell.border。此外,'_where' 必须在

      openpyxl.styles.borders.Side.__elements__
      

      (而不是我的解决方案中的那个,它只是一个子集)。同样,可能会更好,但它确实有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多