Advertisement
Guest User

csv2xlsx using uno

a guest
Aug 28th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 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('.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.  
  44. cmd = "localc \"--accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager\" --nologo --headless --nofirststartwizard"
  45.  
  46. pid = os.fork()
  47.  
  48. if not pid:
  49.   os.system(cmd)
  50.   sys.exit(1)
  51.  
  52. print ("FORKED pid=%d" % pid)
  53.  
  54. time.sleep(5)
  55.  
  56. # import the OpenOffice component context
  57. local = uno.getComponentContext()
  58. # access the UnoUrlResolver service - this will allow to connect to OpenOffice.org program
  59. resolver = 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
  61. context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager")
  62. remoteContext = context.getPropertyValue("DefaultContext")
  63.  
  64. # service responsible for the current document called desktop
  65. desktop = context.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext)
  66. document = desktop.getCurrentComponent()
  67.  
  68. for f in sys.argv[1:]:
  69.   conv(f)
  70.  
  71. desktop.terminate()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement