使用Python3更改LibreOffice Calc中的行高和列宽



我想从Python3程序中编写一个LibreOffice Calc文档。使用pyoo,我几乎可以做任何我想做的事情,包括格式化和合并单元格。但是我不能调整行高和列宽。

我发现改变列宽和行高非常有用,并一直在试验它,但我似乎不能得到我想要的结果。基于上面提到的答案,我现在的测试文件看起来像这样:

#! /usr/bin/python3
import os, pyoo, time, uno
s = '-'
while s != 'Y':
s = input("Have you remembered to start Calc? ").upper()
os.popen("soffice --accept="socket,host=localhost,port=2002;urp;" --norestore --nologo --nodefault")
time.sleep(2)
desktop = pyoo.Desktop('localhost', 2002)
doc = desktop.create_spreadsheet()
class ofic:
sheet_idx = 0
row_num = 0
sheet = None
o = ofic()
uno_localContext = uno.getComponentContext()
uno_resolver = uno_localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", uno_localContext )
uno_ctx = uno_resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
uno_smgr = uno_ctx.ServiceManager
uno_desktop = uno_smgr.createInstanceWithContext( "com.sun.star.frame.Desktop", uno_ctx)
uno_model = uno_desktop.getCurrentComponent()
uno_controller = uno_model.getCurrentController()
uno_sheet_count = 0
doc.sheets.create("Page {}".format(1), index=o.sheet_idx)
o.sheet = doc.sheets[o.sheet_idx]
o.sheet[0, 0].value = "The quick brown fox jumps over the lazy dog"
o.sheet[1, 1].value = o.sheet_idx
uno_controller.setActiveSheet(uno_model.Sheets.getByIndex(uno_sheet_count))
uno_sheet_count += 1
uno_active_sheet = uno_model.CurrentController.ActiveSheet
uno_columns = uno_active_sheet.getColumns()
uno_column = uno_columns.getByName("B")
uno_column.Width = 1000

上面的主要问题是我在屏幕上有2个Calc文档,其中一个是在Python程序开始之前创建的;另一个是从Python用pyoo函数创建的。第一个文档获取列宽度更改,第二个文档接收文本输入等。我只想要第二个文档,当然我想要改变它的列宽度。

我相信答案一定相当简单,但是经过几个小时的实验,我仍然找不到它。有人能给我指个正确的方向吗?

您的代码在pyoo和直接的Python-UNO之间交替,因此它会产生混乱的结果也就不足为奇了。任选其一。就我个人而言,我直接使用python - unix,并没有看到添加额外的pyoo库的好处。

另一个是从Python用pyoo函数

创建的

你是指你问题中的这行代码吗?这是"第二份文档"吗?想要应用列更改的对象?

doc = desktop.create_spreadsheet()

如果是,则从该文档中获取对象,而不是从桌面碰巧选择的窗口中获取对象。

controller = doc.getCurrentController()
sheets = doc.getSheets()

或者您想要另一个文档,不是由Python创建的文档。在这种情况下,在创建第二个文档之前获取对该文档的引用。

first_doc = uno_desktop.getCurrentComponent()
second_doc = desktop.create_spreadsheet()
controller = first_doc.getCurrentController()
sheets = first_doc.getSheets()

如果您没有文档的引用,您可以通过遍历打开的窗口来找到它。

oComponents = desktop.getComponents()
oDocs = oComponents.createEnumeration()

最后,如何调整列的大小。你问题中的链接是Excel和VBA(都来自微软),所以我不确定为什么你认为这是相关的。下面是一个Python-UNO调整列大小的示例。

oColumns = oSheet.getColumns()
oColumn = oColumns.getByName("A")
oColumn.Width = 7000
oColumn = oColumns.getByName("B")
oColumn.OptimalWidth = True

最新更新