Advertisement
Guest User

xlsx2csv python2 uno example

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