python3和libre office calc - 设置列宽

时间:2018-04-27 15:44:59

标签: python-3.x libreoffice-calc

我使用pyoo生成报告作为开放文档电子表格。 pyoo可以做我需要的所有条形设置列宽。有些我想设置为常量,有些则设置为最佳宽度。来自pyoo网站(https://github.com/seznam/pyoo):“如果缺少某些重要功能,那么UNO API始终可用。”

几个小时的谷歌搜索让我上课了com.sun.star.table.TableColumn,它来自this page似乎有我需要的属性(“宽度”和“OptimalWidth”),但是 - < / p>

>>> x = uno.getClass('com.sun.star.table.TableColumn')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/uno.py", line 114, in getClass
    return pyuno.getClass(typeName)
uno.RuntimeException: pyuno.getClass: uno exception com.sun.star.table.TableColumn is unknown

我不知道如何让它发挥作用。 UNO的文件至少可以说是过分......

任何线索都会受到极大的赞赏。

2 个答案:

答案 0 :(得分:1)

示例Python-UNO代码:

def resize_spreadsheet_columns():
    oSheet = XSCRIPTCONTEXT.getDocument().getSheets().getByIndex(0)
    oColumns = oSheet.getColumns()
    oColumn = oColumns.getByName("B")
    oColumn.IsVisible = False
    oColumn = oColumns.getByName("C")
    oColumn.Width = 7000
    oColumn = oColumns.getByName("D")
    oColumn.OptimalWidth = True

文档:

修改

从评论中,您似乎需要完成Python-UNO的入门教程。试试http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html

答案 1 :(得分:0)

谢谢Jim K,你指出我正确的方向,我让它工作。我的python脚本生成了一个十张电子表格,手动调整列宽正变得很痛苦。如果有人想评论或需要解决方案,我会在最终代码下面发布。结合原始的UNO调用和pyoo,它看起来像是一顿猪早餐,但我觉得它很有效。

#! /usr/bin/python3.6

import os, pyoo, time, uno

s = '-'
while s != 'Y':
    s = input("Have you remembered to start Calc? ").upper()

os.system("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

for i in range(5):
    doc.sheets.create("Page {}".format(i+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("A")
    uno_column.OptimalWidth = True
    uno_column = uno_columns.getByName("B")
    uno_column.Width = 1350

    o.sheet_idx += 1

doc.save("whatever.ods")
doc.close()