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

时间:2015-03-06 13:21:48

标签: python macros spreadsheet libreoffice uno

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

1 个答案:

答案 0 :(得分:2)

通过搜索stackoverflow多次得到帮助,我想我会发布一个解决问题的解决方案,需要付出很多努力才能解决。 代码将数据拆分为行并插入到光标当前所在的单元格中,并为后续数据的每一行增加下一个插入的行。

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