Пример работы с Libreoffice через python

Модератор: /dev/random

Ответить
Ism
Сообщения: 1261
Статус: Никто, по сути быдло

Пример работы с Libreoffice через python

Сообщение Ism »

Примеров мало, поэтому решил выложить

Сначала запускается сервер Libreoffice

Код: Выделить всё

soffice.exe --calc --norestore --nologo --minimized --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"


Далее скрипт командует сервером

Код:

# -*- coding: utf-8 -*- import sys,uno,unohelper,string from com.sun.star.beans import PropertyValue from com.sun.star.beans.PropertyState import DIRECT_VALUE local = uno.getComponentContext() resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local) context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext") desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context) props = [] props.append(PropertyValue('FilterOptions',0,'UTF8',DIRECT_VALUE)) props.append(PropertyValue('ReadOnly',0,True,DIRECT_VALUE)) props.append(PropertyValue('RepairPackage',0,False,DIRECT_VALUE)) props.append(PropertyValue("Minimized",0,True,DIRECT_VALUE)) #props.append(PropertyValue("Hidden",0,True,DIRECT_VALUE)) Работает некорректн о листами inputFile = "file:///D:/test.xls" document = desktop.loadComponentFromURL(inputFile, "_blank", 0, (tuple(props))) #Выбор листа if hasattr(document, 'getSheets'): print ('Атрибут найден getSheets') sheets = document.getSheets() sheet = sheets.getByName('Лист2') document.CurrentController.setActiveSheet(sheet) #Замена на листе if hasattr(sheet, 'createReplaceDescriptor'): print ('Атрибут найден createReplaceDescriptor') search=sheet.createReplaceDescriptor() search.SearchString='\n' #search.SearchString='ллл' search.ReplaceString='_' search.SearchWords = 0 search.SearchRegularExpression = 1 sheet.replaceAll(search) props = [] props.append(PropertyValue("FilterName",0,"Text - txt - csv (StarCalc)",DIRECT_VALUE)) props.append(PropertyValue("FilterOptions",0,"59,34,76,1,,0,true,true,false",DIRECT_VALUE)) #Сохранение с параметрами document.storeAsURL("file:///D:/002.csv",(tuple(props))) document.dispose() sys.exit()


Может ком сгодится
Спасибо сказали:
Ism
Сообщения: 1261
Статус: Никто, по сути быдло

Re: Пример работы с Libreoffice через python

Сообщение Ism »

Вариант с проверками и сохранением в html в текст

Код: Выделить всё

# -*- coding: UTF-8 -*-

import sys,uno,os,string,time,codecs
from com.sun.star.beans import PropertyValue
from com.sun.star.beans.PropertyState import DIRECT_VALUE

def convertToURL(cPathname):
    if len( cPathname ) > 1:
        if cPathname[1:2] == ":":
            cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
    cPathname = cPathname.replace("\\", "/")
    cPathname = "file://" + cPathname
    return cPathname

def log_me(Str_):
    print(Str_)
    #file_log=open(sys.argv[4],'w')
    #file_log.write(Str_+'\n')
    #file_log.close()
    return 0

inputFile=sys.argv[1]
outputFile=sys.argv[2]

if os.path.exists(inputFile):
  print('Файл существует '+outputFile)
else:
  print('Файла нет, выход '+outputFile)
  sys.exit()

local = uno.getComponentContext()
resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)

props = []
props.append(PropertyValue("FilterOptions",0,"UTF8",DIRECT_VALUE))
#props.append(PropertyValue("Hidden",0,1,DIRECT_VALUE))
props.append(PropertyValue('ReadOnly',0,True,DIRECT_VALUE))
props.append(PropertyValue('RepairPackage',0,False,DIRECT_VALUE))
props.append(PropertyValue("Minimized",0,True,DIRECT_VALUE))

# Если html , особая обработка
(filepath,filename)=os.path.split(inputFile)
(shortname,FileExt)=os.path.splitext(filename)
if FileExt=='.html':
  log_me(' --> Файл html '+inputFile)
  props.append(PropertyValue("FilterName",0,"calc_HTML_WebQuery",DIRECT_VALUE))

inputFile = convertToURL(inputFile)
outputFile = convertToURL(outputFile)
ExcelListName = sys.argv[3]
try:
  document = desktop.loadComponentFromURL(inputFile, "_blank", 0, (tuple(props))) #
except:
  sys.exit(3)  #Невозможно открыть файл

if len(ExcelListName)<2:
  try:
    sheet = document.CurrentController.getActiveSheet()
  except:
    sys.exit(9) # Невозможно активоровать текущий лист
else:
  try:
    if hasattr(document, 'getSheets'):
      sheets = document.getSheets()
      sheet = sheets.getByName(ExcelListName)
      document.CurrentController.setActiveSheet(sheet)
  except:
    sys.exit(1) # Лист не открыт

if hasattr(sheet, 'createReplaceDescriptor'):
 search=sheet.createReplaceDescriptor()
 search.SearchString='\n'
 #search.SearchString='ллл'
 search.ReplaceString='_'
 search.SearchWords = 0
 search.SearchRegularExpression = 1
 sheet.replaceAll(search)

props = []
props.append(PropertyValue("FilterName",0,"Text - txt - csv (StarCalc)",DIRECT_VALUE))
props.append(PropertyValue("FilterOptions",0,"59,34,76,1,,0,true,true,false",DIRECT_VALUE))

try:
  document.storeAsURL(outputFile,(tuple(props)))
except:
  sys.exit(2)  # Не удалось сохранить
#time.sleep(2000)
document.dispose()

sys.exit(0)
Спасибо сказали:
Ответить