如何在libreofficepython宏中测试我是在Writer还是Calc文档中?

2024-04-25 05:16:01 发布

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

我在libreoffice工作,需要一个python宏,可以从外部源将数据插入当前文档。
考虑到使用unoapi的电子表格和文档的insert方法不同,如何编写宏以发现我是在writer文档中还是在calc电子表格中,并针对文档类型使用适当的insert方法?在


Tags: 数据方法文档类型libreofficecalcwriter电子表格
1条回答
网友
1楼 · 发布于 2024-04-25 05:16:01
def fs2InvoiceNo(*args):
#get the doc from the scripting context which is made available to all scripts
    desktop = XSCRIPTCONTEXT.getDesktop()                                      
    model = desktop.getCurrentComponent()
#get the XText interface
    method = ""
    try:
        text = model.Text
        tRange = text.End
        cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
        oTable = cursor.TextTable
        oCurCell = cursor.Cell
        method = "Doc"
    except:
        pass
    try:
        sheets = model.getSheets()
        sheet = model.CurrentController.getActiveSheet()
        oSelection = model.getCurrentSelection()
        oArea = oSelection.getRangeAddress()
        first_row = oArea.StartRow
        last_row = oArea.EndRow
        first_col = oArea.StartColumn
        last_col = oArea.EndColumn
        method = "Calc"
    except:
        pass
    if method == "":
        raise Exception("Unknown environment for this script")
#and get the string from Footswitch2 via a TCP port
    import os, socket, time
    from configobj import ConfigObj
    configuration_dir = os.environ["HOME"]
    config_filename = configuration_dir + "/fs2.cfg"
    if  os.access(config_filename, os.R_OK):
        pass
    else:
        return None
    cfg = ConfigObj(config_filename)
    #define values to use from the configuration file
    tcp_port = int(cfg["control"]["TCP_PORT"])
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    try:
        sock.connect(("localhost", tcp_port))
    except:
        return None
    sock.settimeout(0.5)
    try:
        sock.send(bytes('invoicenumber\n', 'UTF-8'))
    except:
        return None
    try:
        time.sleep(0.2)
        s_list = sock.recv(1024).decode('UTF-8')
        s_list = s_list.split("\n")
    except:
        return None
    lines_in_response = len(s_list)
    if lines_in_response is None:
        return None
    invoice_no = s_list[0]
    if invoice_no == "":
        invoice_no = "None"
    if method == "Doc":
        if oCurCell == None: # Are we inserting into a table or not?
            text.insertString(cursor, invoice_no, 0)
        else:
            cell = oTable.getCellByName(oCurCell.CellName)
            cellCursor = cell.createTextCursor() # use this cursor if you want the text inserted at the beginning of the cell
            cell.insertString(cursor, invoice_no, False) # use the standard cursor to insert at the current position
    else:
        cell = sheet.getCellByPosition(first_col, first_row)
        cell.String = invoice_no
    sock.close()
    return None

相关问题 更多 >