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

时间:2015-03-07 18:53:52

标签: python macros libreoffice uno

我在libreoffice工作,需要一个可以从外部源将数据插入当前文档的python宏。
鉴于电子表格和使用UNO API的文档的插入方法不同,如何编写宏来发现我是在编写器文档还是计算电子表格中,并使用适当的插入方法来处理文档类型? / p>

1 个答案:

答案 0 :(得分:0)

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