如何在LibreOffice Calc中使用PyUNO更改单元格边框的线宽?

2024-09-29 17:10:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本来自动调整LibreOffice Calc中的单元格边框。我想我知道需要更改哪些属性,但是当我为该属性指定一个新值时,该值不会更改

例如,我编写此代码是为了将单个单元格的TopLine.LineWidth从0更改为10

# Access the current calc document
model = desktop.getCurrentComponent()
# Access the active sheet
active_sheet = model.CurrentController.ActiveSheet
# Get the cell and change the value of LineWidth
cell = active_sheet.getCellByPosition(2, 2)
cell.TableBorder2.TopLine.LineWidth = 10

运行此代码后,我没有收到任何错误。我还确保我正在访问我希望修改的单元格。但是,此代码不会更改单元格的边框宽度

我尝试通过在赋值前后打印值来进行一些调试:

# This first print statement returns 0 because the cell has no borders
print(cell.TableBorder2.TopLine.LineWidth)
cell.TableBorder2.TopLine.LineWidth = 10
# This second print statement still returns 0, but I was expecting it to return 10
print(cell.TableBorder2.TopLine.LineWidth)

有人知道我做错了什么吗


Tags: the代码model属性accesscellthissheet
2条回答

所以,在做了大量研究之后,我发现了至少三种改变边界设置的方法。因为这花费了我太多的精力,我想我应该把它们留在这里,这样将来其他人可能会更容易找到答案

在所有示例中,我将单个单元格上边框的线宽设置为10

方法1:使用getPropertyValue()和setPropertyValue()

cell = active_sheet.getCellByPosition(1, 1)
border_prop = cell.getPropertyValue("TopBorder")
border_prop.LineWidth = 10
cell.setPropertyValue("TopBorder", border_prop)

方法2(源自Jim K的答案)

cell = active_sheet.getCellByPosition(1, 1)
border_prop = cell.TopBorder2
border_prop.LineWidth = 10
cell.TopBorder2 = border_prop

方法3:使用BorderLine2结构

border_prop = uno.createUnoStruct("com.sun.star.table.BorderLine2")
border_prop.LineWidth = 10
cell = active_sheet.getCellByPosition(1, 1)
cell.setPropertyValue("TopBorder", border_prop)

您需要将“单元”属性设置为已更改的边框对象。从https://ask.libreoffice.org/en/question/145885/border-macro-no-longer-works/

aThinBorder = oRange.TopBorder2
aThinBorder.LineWidth = 1
oRange.TopBorder2 = aThinBorder

相关问题 更多 >

    热门问题