· 5 years ago · Aug 28, 2020, 02:26 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('.csv','.xlsx')
28 if fi == fo:
29 desktop.terminate()
30 raise BaseException("OOPS [%s]" % fi)
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, _toProperties(FilterName="scalc: Text - txt - csv (StarCalc)", FilterOptions="44,34,76,1"))
37 document.calculateAll()
38
39 # csv
40 #document.storeToURL(outputFile, _toProperties(FilterName="Text - txt - csv (StarCalc)", FilterOptions="44,34,76,1"))
41 #document.storeToURL(outputFile, _toProperties(FilterName="calc_MS_Excel_40"))
42 document.storeToURL(outputFile, _toProperties(FilterName="Calc MS Excel 2007 XML"))
43
44cmd = "localc \"--accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager\" --nologo --headless --nofirststartwizard"
45
46pid = os.fork()
47
48if not pid:
49 os.system(cmd)
50 sys.exit(1)
51
52print ("FORKED pid=%d" % pid)
53
54time.sleep(5)
55
56# import the OpenOffice component context
57local = uno.getComponentContext()
58# access the UnoUrlResolver service - this will allow to connect to OpenOffice.org program
59resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
60# load the context and you are now connected - you can access OpenOffice via its API mechanism
61context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager")
62remoteContext = context.getPropertyValue("DefaultContext")
63
64# service responsible for the current document called desktop
65desktop = context.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext)
66document = desktop.getCurrentComponent()
67
68for f in sys.argv[1:]:
69 conv(f)
70
71desktop.terminate()