如何在 libreoffice calc 中编写 python 宏来发送和接收数据

How do I write a python macro in libreoffice calc to send and receive data

前提:我在 libreoffice calc 中工作,需要通过宏向我知道正在侦听 TCP 端口的另一个程序发送指令。 我期待监听程序的回复,并希望将回复数据插入到 libreoffice 电子表格中。

通过搜索 Whosebug 得到了多次帮助,我认为我会 post 解决一个需要很多努力才能解决的问题。 该代码将数据拆分成行并插入到光标当前所在的单元格中,并且对于后续数据的每一行,都会增加下一次插入的行。

Configobj 是一个从平面文件中读取参数的包。在此示例中,我使用该文件来存储要使用的 TCP 端口。监听程序和这段代码都从同一个配置文件中读取端口号。它可能是硬编码的。

这是一个适合我的 python 宏,我相信它会为其他人指明正确的方向。

def fs2ClientdataCalc(*args):

    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    try:
        sheets = model.getSheets()
    except AttributeError:
        raise Exception("This script is for Calc Spreadsheets only")
    #sheet = sheets.getByName('Sheet1')
    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
    #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(10)
    try:
        sock.send(bytes('client\n', 'UTF-8'))
    except:
        return None
    try:
        time.sleep(1.0)
        s_list = sock.recv(4096).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
    column =['A','B','C','D','E','F','G','H','I','J','K','L','M',\
             'N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    for x in range(0,lines_in_response):
        insert_table = s_list[x].split("\n")
        parts = len(insert_table)
        for y in range(0,parts):
            it = insert_table[y]
            cell_name = column[first_col + y]+str(x +1 +first_row)
            cell = sheet.getCellRangeByName(cell_name)
            cell.String = it

    sock.close()
    return None