Office Automation/es

From Free Pascal wiki
Revision as of 20:06, 7 November 2009 by Iskraelectrica (talk | contribs) (New page: {{Office Automation}}    La capacidad de interactuar con los programas ofimáticos y así generar hojas de cálculo, documentos de texto y presentaciones desde nuestro cód...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) italiano (it) русский (ru) 中文(中国大陆)‎ (zh_CN)

   La capacidad de interactuar con los programas ofimáticos y así generar hojas de cálculo, documentos de texto y presentaciones desde nuestro código puede ser muy valiosa en la oficina, y ahorrar mucho tiempo a aquellos que hagan. Un ejemplo es la creación de aplicaciones que pueden leer archivos en un formato arbitrario y guardar la salida en un archivo de Excel, una tarea mucho más eficiente de hacer con el código a continuación expuesto que de forma manual.

Utilizando UNO Bridge de OpenOffice

   OpenOffice tiene enlaces para lenguaje como C, Java, JavaScript y Python. En Windows, OpenOffice también puede ser manipulado en Pascal a través de automatización COM (véase más adelante), pero actualmente no una forma sencilla de usar OpenOffice UNO (Universal Network Objects -Objetos Universales de Red-) desde Pascal en OS X y Linux. Si estás interesado en el desarrollo de un puente entre OO y Pascal, por favor mira estos enlaces para más información (precaución: estos enlaces son muy técnicos al estilo SUN):

api.openoffice.org

About_Bridges

Ver también el tema más abajo sobre Python.

Usar automatización COM para interactuar con OpenOffice y Microsoft Office

Automation is unique to Windows so the following two examples won't work on OS X or Linux. For those platforms, please refer to Making do without Windows COM Automation. If you only need to create and/or view a word processing document from your program, take a look at the XDev Toolkit.

Here's a simple example of how to open a document with your program using the OpenOffice Automation server. Note that this works only on Windows.

program TestOO;

{$IFDEF FPC}
 {$MODE Delphi}
{$ELSE}
 {$APPTYPE CONSOLE}
{$ENDIF} 

uses
  SysUtils, Variants, ComObj;

const
  ServerName = 'com.sun.star.ServiceManager';
var          
  Server     : Variant;
  Desktop    : Variant;
  LoadParams : Variant;
  Document   : Variant;
  TextCursor : Variant;
begin
  if Assigned(InitProc) then
    TProcedure(InitProc);

  try
    Server := CreateOleObject(ServerName);
  except
    WriteLn('Unable to start OO.');
    Exit;
  end;

  Desktop := Server.CreateInstance('com.sun.star.frame.Desktop');

  LoadParams := VarArrayCreate([0, -1], varVariant);

   {Create new document}
  Document := Desktop.LoadComponentFromURL('private:factory/swriter',
                                           '_blank', 0, LoadParams);

  TextCursor := Document.Text.CreateTextCursor;

   {Insert existing document}  //Substitute your path and doc
  TextCursor.InsertDocumentFromURL('file:///C|/my/path/mydoc.doc',  
                                   LoadParams);
end.

Here's a simple example of how to open a document with your program using the Word Automation server. Note that this example works only on Windows and only when compiled with Delphi; Free Pascal 2.2.2 can now compile the code but running it does not work. Please check back later or test with a future version of FPC.

program TestMsOffice;

{$IFDEF FPC}
 {$MODE Delphi}
{$ELSE}
 {$APPTYPE CONSOLE}
{$ENDIF} 

uses
  SysUtils, Variants, ComObj;

const
  ServerName = 'Word.Application';
var
  Server     : Variant;
begin
  if Assigned(InitProc) then
    TProcedure(InitProc);

  try
    Server := CreateOleObject(ServerName);
  except
    WriteLn('Unable to start Word.');
    Exit;
  end;

   {Open existing document}  //Substitute your path and doc
  Server.Documents.Open('c:\my\path\mydoc.doc'); 

  Server.Visible := True;  {Make Word visible}

end.


Attempting to use Python to manipulate OpenOffice

Since OpenOffice includes support for Python, it would seem possible to run Python scripts from Pascal to manipulate OO, in lieu of actual Pascal language bindings. Here are the steps for one possible approach to doing this:

  1. Test UNO via Python macro run within OO
  2. Test UNO via Python standalone script
  3. Support for running Python scripts in Pascal
  4. Test UNO via Python script run in Pascal
  5. Pascal class that wraps Python UNO

Note: The following scripts were tested with OpenOffice 2.3.1 on Windows XP and NeoOffice 2.2.5 Patch 6 on Mac OS X 10.4.11 (PowerPC).

Step 1. Test UNO via Python macro run within OO

OO has tools for creating JavaScript macros, but not Python macros, so use a text editor to save the following script to file test_macro.py and place it in OO's user macro folder. On Windows, this folder is:

C:\Document and Setting\<username>\Application Data\OpenOffice.org2\user\Scripts\python\Library1

On Mac OS X, this folder is:

~/Library/Preferences/NeoOffice-2.2/user/Scripts/python/Library1

On both platforms, you'll need to create the python/Library1 folder.

Here is the code for test_macro.py, adapted from the OO Pascal example above:

# Python macro that tests UNO by creating new document and inserting some text.

import uno

def TestNewDoc():
  ctx = uno.getComponentContext()
  smgr = ctx.ServiceManager
  desktop = smgr.createInstance('com.sun.star.frame.Desktop')
  doc = desktop.loadComponentFromURL('private:factory/swriter', '_blank', 0, ())
  textCursor = doc.Text.createTextCursor()
  doc.Text.insertString(textCursor, 'Hello World', 0)

In OO, choose Tools | Macros | Organize Macros | Python and run the macro to make sure it works.

Step 2. Test UNO via Python standalone script

Here is the same code as a standalone script:

# Python script that tests UNO by creating new document and inserting some text.

import sys

if sys.platform == 'darwin':
  sys.path.append('/Applications/NeoOffice.app/Contents/MacOS')

import officehelper

ctx = officehelper.bootstrap()
smgr = ctx.ServiceManager
desktop = smgr.createInstance('com.sun.star.frame.Desktop')
doc = desktop.loadComponentFromURL('private:factory/swriter', '_blank', 0, ())
textCursor = doc.Text.createTextCursor()
doc.Text.insertString(textCursor, 'Hello World', 0)

Save this to file test.py and run it like this on Windows from a command line. Note: On Windows and Linux, use the version of Python included with OO; on Mac OS X, use the system's Python 2.3.

"\program files\openoffice.org 2.3\program\python" test.py

On Mac OS X, run the script like this from a Terminal window:

#!/bin/sh
export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH":/Applications/NeoOffice.app/Contents/MacOS"
python2.3 test.py

Unfortunately, this script doesn't work either on Windows or Mac OS X. On Windows, it displays an error dialog with no text (!) and then outputs an error message to the console that says "Cannot connect to soffice server". On Mac OS X, it starts NeoOffice and creates the new document, then NeoOffice shuts down abruptly.

UNO Python To-Do

Obviously additional investigation is needed before we can proceed to step 3. You are welcome to work on this. Here are a couple things to try:

  • Test on Linux
  • Test on more recent versions of OpenOffice
  • Jan. 5, 2009: Results of testing OpenOffice 3 on Windows:
    • OO 3.0.0 support for user Python macros is broken (Step 1); fixed with OO 3.0.1 RC1.
    • Step 2 no longer displays the empty error dialog and the console exception message is different, but still doesn't start OO.
    • Note that paths to various parts of OO and to user macros have changed with OO 3.



Using the Free Pascal Spreadsheet Library

Another way to automate repetitive work with spreadsheets is to use the FPSpreadsheet library. It can read and write spreadsheets in several formats and it doesn't require having any external application installed on the machine.

Writing an Excel file using ADO

please write me.

Read/Writing an Excel file using the Excel Interface Component

The component is available here: http://tcoq.free.fr/composants.html

Since Automation is not yet available, but COM is available, the Excel interface component provides a set of Lazarus classes encapsulating calls to the Excel COM interface (the one below the Automation). It hides most of the drudgery of working with low-level code.

Functionality:

- creating and loading excel workbooks,

- saving workbooks,

- creating and accessing sheets,

- getting values and setting values (and formulas) in cells,

- getting and changing color of cells,

- getting and changing column height and row width,

- creating comments,

- creating shapes,

- creating charts.


Getting a sheet is simple:

 // Initializing the common excel workbook:
 ExcelApp := TExcelApplication.Create(nil);
 ExcelApp.Active := True;
 ExcelApp.Visible := True;
 ExcelWbs := ExcelApp.WorkBooks;
 ExcelWb := ExcelWbs.Open( TestFileName)
 ExcelSheets := ExcelWb.Sheets;
 ExcelSheet1 := ExcelSheets.Sheet('Sheet1');

Playing around with cells is simple too:

 // adding a value
 aCell := aSheet.Cells(1, 1);
 aCell.Value := 10;
 // adding a formula
 aCell := aSheet.Cells(2,1);
 aCell.Formula := '=A1+10';
 // getting the value computed in Excel
 aValue := aCell.Value;


The test case provided has many more examples.

External links


Traducido por Iskraelectrica