· 5 years ago · Aug 28, 2020, 02:24 PM
1#!/usr/bin/env python2
2import sys
3import os
4from os.path import abspath, isfile, splitext
5import signal
6import time
7
8sys.path.append('/usr/lib64/libreoffice/program')
9import uno
10from com.sun.star.beans import PropertyValue
11
12def _toProperties(**args):
13 props = []
14 for key in args:
15 prop = PropertyValue()
16 prop.Name = key
17 prop.Value = args[key]
18 props.append(prop)
19 return tuple(props)
20
21# start first
22# libreoffice --headless --accept="socket,host=0,port=8100,tcpNoDelay=1;urp"
23
24
25def conv(fi):
26 print ("CONVERT %s" % fi)
27 fo = fi.replace('.xlsx','.csv')
28 if fi == fo:
29 desktop.terminate()
30 raise BaseException("OOPS [%s] == [%s]" % (fi, fo))
31
32 inputFile = uno.systemPathToFileUrl(abspath(fi))
33 outputFile = uno.systemPathToFileUrl(abspath(fo))
34
35 # load, calculateAll(), save
36 document = desktop.loadComponentFromURL(inputFile, "_blank", 0, ())
37 document.calculateAll()
38
39 # csv
40 document.storeToURL(outputFile, _toProperties(FilterName="Text - txt - csv (StarCalc)", FilterOptions="44,34,76,1"))
41
42cmd = "localc \"--accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager\" --nologo --headless --nofirststartwizard"
43
44pid = os.fork()
45
46if not pid:
47 os.system(cmd)
48 sys.exit(1)
49
50print ("FORKED pid=%d" % pid)
51
52time.sleep(5)
53
54# import the OpenOffice component context
55local = uno.getComponentContext()
56# access the UnoUrlResolver service - this will allow to connect to OpenOffice.org program
57resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
58# load the context and you are now connected - you can access OpenOffice via its API mechanism
59context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager")
60remoteContext = context.getPropertyValue("DefaultContext")
61
62# service responsible for the current document called desktop
63desktop = context.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext)
64document = desktop.getCurrentComponent()
65
66for f in sys.argv[1:]:
67 conv(f)
68
69desktop.terminate()
70