Advertisement
Guest User

xlsx2csv using uno

a guest
Aug 28th, 2020
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. import sys
  3. import os
  4. from os.path import abspath, isfile, splitext
  5. import signal
  6. import time
  7.  
  8. sys.path.append('/usr/lib64/libreoffice/program')
  9. import uno
  10. from com.sun.star.beans import PropertyValue
  11.  
  12. def _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.  
  25. def 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.  
  42. cmd = "localc \"--accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager\" --nologo --headless --nofirststartwizard"
  43.  
  44. pid = os.fork()
  45.  
  46. if not pid:
  47.   os.system(cmd)
  48.   sys.exit(1)
  49.  
  50. print ("FORKED pid=%d" % pid)
  51.  
  52. time.sleep(5)
  53.  
  54. # import the OpenOffice component context
  55. local = uno.getComponentContext()
  56. # access the UnoUrlResolver service - this will allow to connect to OpenOffice.org program
  57. resolver = 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
  59. context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager")
  60. remoteContext = context.getPropertyValue("DefaultContext")
  61.  
  62. # service responsible for the current document called desktop
  63. desktop = context.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext)
  64. document = desktop.getCurrentComponent()
  65.  
  66. for f in sys.argv[1:]:
  67.   conv(f)
  68.  
  69. desktop.terminate()
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement