From Apache OpenOffice Wiki
Jump to: navigation, search
PyUNO Logo

The PyUNOServer is a script that works as an XML server for Calc where it can exchange data through XML calls. This means that can get data from other apps that are XML compliant. You can download the script from this mirror since the original site seems to be down.

The zip file contains 3 files:

  • - The Python Script
  • PyUNOServerV2.pyc - compiled version
  • PyUNOServer.sh2 - the script to conect to the service

The script have just 1 script called however there is a faster, bytecode-compiled script. It also includes a bash script which loads the path to the application.

NOTE: This script will work on just certain distros since the location of might vary. We recomend to load the path manually.

This script uses the following libraries:

  • OS - This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like posix or nt.
  • UNO - Python UNO implementation module, this can used by python 2.3.4 only which is the python provided within It provides all the interfaces from into python.
  • SYS - This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
  • time - This module provides various time-related functions. It is always available, but not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
  • logging - Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a name space hierarchy using dots (periods) as separators.
  • urllib - This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply -- it can only open URLs for reading, and no seek operations are available.
  • SimpleXMLRPCServer - The SimpleXMLRPCServer module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.

# -*- coding: iso-8859-1 -*-
# pyUnoServer - version 2.0
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import os
import uno
import sys
import time
import logging
import urllib
class PyUNOServer(SimpleXMLRPCServer):
	def _dispatch(self, method, params):
			func = getattr(self, '' + method)
			self.logger.error("El Metodo '"+method+"' no esta soportado!")
			raise Exception('method "%s" is not supported' % method)
				ret = func(*params)"Llamada: %s%s | Retorno: %s" % (method, params, ret))
				return ret
			except:"Llamada: %s%s" % (method, params))
				self.logger.error("Error: %s:%s" % sys.exc_info()[:2])
	def init(self):
		This method	starts an Openoffice session and initializes the XMLRPC server
		# Generate some useful constants
		self.EMPTY = uno.Enum("", "EMPTY")
		self.TEXT = uno.Enum("", "TEXT")
		self.FORMULA = uno.Enum("", "FORMULA")
		self.VALUE = uno.Enum("", "VALUE")
		# Generate a Logger
		self.logger = logging.getLogger('pyUnoServer')
		hdlr = logging.FileHandler('./pyUnoServer.log')
		formatter = logging.Formatter('%(asctime)s %(levelname)s -- %(message)s')
		self.sessions = []
		self.sessionSerial = 0
		# Start Calc and grep the PID
		self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")"OOCalc Iniciado con el PID %d" % self.PID)
		while 1:
				localContext = uno.getComponentContext()
				resolver = localContext.ServiceManager.createInstanceWithContext("", localContext )
				smgr = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" )
				remoteContext = smgr.getPropertyValue( "DefaultContext" )
				self.desktop = smgr.createInstanceWithContext( "",remoteContext)"Sistema conectado al socket de UNO")
	def openSession(self, session):
		This method opens a new session.
		Sample usage from PHP:
		 - $sessionString is your a session ID provided by your program):
			$openSession = array( new XML_RPC_VALUE($sessionString, "string"));
			$sessionID = queryXMLRPC($client, "openSession", $openSession);
			return $sessionID;
		for i,x in enumerate(self.sessions):
			if x[0] == session:
				currentSerial = i
			currentSerial = len(self.sessions)-1
		return currentSerial
	def getSessions(self):
		return self.sessions
	def openBook(self, session, bookPath):
		This method opens a new Openoffice spreadsheet book.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $path is the path to the book in the server's filesystem
		$openBookQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($path,"string") );
		$bookID = queryXMLRPC($client, "openBook", $openBookQuery);
		return $bookID;
		currentSerial = session
		bookPath = bookPath.strip()
		print bookPath
		exists = os.path.exists(bookPath)
		if exists == False:
			raise Exception('El libro %s no existe', bookPath)
		else:"se ha encontrado el libro!")
		currentBook = -1
		for i, book in enumerate(self.sessions[currentSerial][1]):
				bookname = book[0]
				bookhandler = book[1]
				bookmodtime = book[2]
				if bookname == bookPath:
					modtime = os.path.getmtime(bookPath)
					if modtime > bookmodtime:
						currentBook = i
				self.logger.error("El libro "+currentBook+" no existe!")
		if currentBook < 0:
			handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
			if handler == None:
				raise Exception('El libro no existe o tiene caracteres extraños...')
			modtime = os.path.getmtime(bookPath)
			estruct = [bookPath,handler,modtime]
			currentBook = len(self.sessions[currentSerial][1])-1
		return currentBook
	def closeBook(self, sessionID, bookID):
		books = self.sessions[sessionID][1]
		# Close the document. It doesn't look very elegant but thats the way is documented.
		return 1
	def getBookSheets(self, sessionID, bookID):
		This method return an array with the book's worksheets.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		$sheetsQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($bookID, "int") );
		$sheets = queryXMLRPC($client, "getBookSheets" , $sheetsQuery);
		return $sheets;
		sheets = self.sessions[sessionID][1][bookID][1].getSheets().createEnumeration()
		container = []
		while sheets.hasMoreElements():
			currentSheet = sheets.nextElement()
		return container
	def getCellValue (self,sheet,x,y):
		cell = sheet.getCellByPosition(x,y)
		cellType  = cell.getType()
		if cellType == self.TEXT :
			data = cell.getString().encode("UTF-8")
			if data == None:
				return ""
			return data.encode("UTF-8")
		if cellType == self.FORMULA or cellType == self.VALUE :
			data = cell.getValue()
			if data == None:
				return 0
			return cell.getValue()
		if cellType == self.EMPTY :
			return ""
	def getCell(self, session, book, sheet, x, y):
		This method returns the content of a cell.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		 - $sheet is the sheet's ID as returned by getBookSheets()
		$query = array(	
						new XML_RPC_Value($sessionID, "int"), 
						new XML_RPC_VALUE($bookID, "int"), 
						new XML_RPC_VALUE($sheet, "int"), 
						new XML_RPC_Value($x, "int"), 
						new XML_RPC_Value($y, "string")
		$result = queryXMLRPC($client, "getCell", $query);
		return $result;
		sheetref = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
		valor = self.getCellValue(sheetref,x,y)
		return valor
	def setCell(self,session,book,sheet,x,y,value):
		This method sets the content of a cell.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		 - $sheet is the sheet's ID as returned by getBookSheets()
		$query = array(
						new XML_RPC_Value($sessionID, "int"), 
						new XML_RPC_VALUE($bookID, "int"), 
						new XML_RPC_VALUE($sheet, "int"), 
						new XML_RPC_Value($x, "int"), 
						new XML_RPC_Value($y, "int"),
						new XML_RPC_Value($value, "string")
		$result = queryXMLRPC($client, "setCell", $query);
		return $result;
		bookObject = self.sessions[session][1][book][1]
		cell = bookObject.getSheets().getByIndex(sheet).getCellByPosition(x,y)
		return 1
	#what will change? mmm...
	def massiveSetCell(self, data):
			for valores in data:
				session,sheetid,x,y,valor = valores.split("|")
				code = self.setCell(self.trim(session),self.trim(sheetid),self.trim(x),self.trim(y),valor)
				if code < 0:
					return code
			return 1
	def getSheetPreview(self,session,book,sheet):
		sheet = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
		range = sheet.getCellRangeByPosition(0,0,8,23).getDataArray()
		return range
	def trim(self, cadena):
		return cadena.strip()
server = PyUNOServer(("localhost", 8000))
server.init()"Servicio Inicializado...")
except KeyboardInterrupt:"Cerrando el socket...")
	os.kill(server.PID,1)"Socket cerrado.")


export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
export PYTHONPATH=$PYTHONPATH:/usr/lib/openoffice/program
export DISPLAY=localhost:1
echo "Logging en pyUnoServer.log"
echo "Ciao!"
Personal tools