0

我试图在 openoffice 文档中定义“变量”,但我一定做错了什么,因为当我尝试使用字段显示变量的值时,我只得到一个空字符串。

这是我正在使用的代码(使用 Python UNO 桥)。有趣的是第二个功能。

import time
import subprocess
import logging
import os
import sys
import uno
from com.sun.star.text.SetVariableType import STRING

def get_uno_model(): # helper function to connect to OOo. Only interesting 
                     # if you want to reproduce the issue locally, 
                     # don't spend time on this one
    try:
        model = XSCRIPTCONTEXT.getDocument()
    except NameError:
        pass # we are not running in a macro
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()

    # create the UnoUrlResolver
    resolver = localContext.ServiceManager.createInstanceWithContext(
                                    "com.sun.star.bridge.UnoUrlResolver", localContext )

    # connect to the running office
    try:
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
                               "urp;StarOffice.ComponentContext")
    except:
        cmd = ['soffice', '--writer', '-accept=socket,host=localhost,port=2002;urp;']
        popen = subprocess.Popen(cmd)
        time.sleep(1)
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
                               "urp;StarOffice.ComponentContext")
    smgr = ctx.ServiceManager

    # get the central desktop object
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)

    # access the current writer document
    model = desktop.getCurrentComponent()
    return model

def build_variable(model, name, value):
    # find or create a TextFieldMaster with the correct name
    master_prefix = u"com.sun.star.text.fieldmaster.SetExpression"
    variable_names = set([_name.split('.')[-1] 
                          for _name in model.TextFieldMasters.ElementNames
                          if _name.startswith(master_prefix)])
    master_name = u'%s.%s' % (master_prefix, name)
    if name not in variable_names:
        master = model.createInstance(master_prefix)
        master.Name = name
    else:
        master = model.TextFieldMasters.getByName(master_name)

    # create the SetExpression field
    field = model.createInstance(u'com.sun.star.text.textfield.SetExpression')
    field.attachTextFieldMaster(master)
    field.IsVisible = True
    field.IsInput = False
    field.SubType = STRING
    field.Content = value
    return field

model = get_uno_model() # local function to connect to OpenOffice
text = model.Text
field = build_variable(model, u'Toto', 'nice variable')
text.insertTextContent(text.getEnd(), field, False)

这段代码以某种方式工作(除非我删除了太多),但是如果我手动插入一个字段来显示 Toto 的值,我不会得到我期望的“nice variable”字符串,并且插入的字段没有值

4

2 回答 2

0

在创建主字段后,缺少将主字段的 SubType 属性设置为 STRING 的代码。

于 2013-01-16T18:54:40.267 回答
0

尝试

field.CurrentPresentation = value

让我们知道这是否解决了您的问题,谢谢。

于 2013-03-19T09:18:26.873 回答