python 操作 libreoffic

发布时间:2019-08-15 09:56:43编辑:auto阅读(1101)

    最近研究了一个,用python来向libreoffice spreadsheet中的写数据,openoffice管方网站的资料也不是很清楚,

    在网上找到的几个比较有用的网站有:http://wiki.services.openoffice.org/wiki/Python#PyUNO_Modules

    上面了有一个比较好的入门文档:http://lucasmanual.com/mywiki/OpenOffice

    还有一个人在论坛上写的一个比较有用的例子:http://www.oooforum.org/forum/viewtopic.phtml?p=56037#56037

    这个例子非常好,告诉你怎样操作spreadsheet,本人在其它地方没有找到操作spreadsheet的文档,如果哪位网友找到了,留个言,谢谢!

    现在把基本的代码贴过来,其它的请查上面给出的那两个网址即可


    首先要启动libreoffice用下面命令:
    libreoffice -accept="socket,host=localhost,port=2002;urp;"

    Start openoffice so it listens on a port.

    连接:

    import uno

    def connect():
        local = uno.getComponentContext()
        resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
        context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
        desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
       
        return desktop

    class Calc:

        def __init__(self, file_name = "private:factory/swriter"):
            desktop = connect()
            self.doc = desktop.loadComponentFromURL(file_name, "_blank", 0, ())
            self.sheet = self.doc.getSheets().getByIndex(0)

        def get_dic(self, start, end):
           
            for row in range(start - 1, end):
                value = self.sheet.getCellByPosition(0, row).getString()

                self.sheet.getCellByPosition(1, row).setString("have read")

        def save(self):

            self.doc.store()

     

    def main():
        calc_file = "file:///home/zhangliyong/Desktop/2011.xls"

        calc_obj = Calc(calc_file)
        calc_obj.get_dic(5, 46)
        calc_obj.save()

    注意在操作libreoffice文档时,当指写文档路径时前面要加file://

关键字