Difference between revisions of "Office Automation/es"
(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...) |
|||
Line 13: | Line 13: | ||
== Usar automatización COM para interactuar con OpenOffice y Microsoft Office== | == Usar automatización COM para interactuar con OpenOffice y Microsoft Office== | ||
− | + | La automatización COM es exclusiva de Windows, asíq que lso ejemplos que siguen no funcionan ni en OS X ni en Linux. Para estas plataformas ver [http://wiki.lazarus.freepascal.org/Multiplatform_Programming_Guide#Making_do_without_Windows_COM_Automation Prescindiendo de la automatización COM de Windows]. Si sólo necesita crear y/o ver un documento de texto desde su programa, da un vistazo al [http://web.fastermac.net/~MacPgmr/XDev/XDevStatus.html#RTF XDev Toolkit]. | |
− | + | Este es una ejemplo sencillo de cómo abrir un documento con tu programa utilizando el servidor de automatización de OpenOffice. Recuerda que esto sólo funciona en Windows. | |
− | |||
− | |||
− | + | <delphi> program PruebaOpenOffice; | |
− | |||
− | |||
− | |||
− | |||
− | + | {$IFDEF FPC} | |
− | + | {$MODE Delphi} | |
+ | {$ELSE} | ||
+ | {$APPTYPE CONSOLE} | ||
+ | {$ENDIF} | ||
− | + | uses | |
− | + | SysUtils, Variants, ComObj; | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | try | + | const |
− | + | NombreServidor = 'com.sun.star.ServiceManager'; | |
− | + | var | |
− | + | Servidor : Variant; | |
− | + | Escritorio : Variant; | |
− | + | ParametrosCarga : Variant; | |
+ | Documento : Variant; | ||
+ | CursorTexto : Variant; | ||
+ | begin | ||
+ | if Assigned(InitProc) then | ||
+ | TProcedure(InitProc); | ||
+ | |||
+ | try | ||
+ | Servidor := CreateOleObject(NombreServidor); | ||
+ | except | ||
+ | WriteLn('No puedo arrancar OpenOffice.'); | ||
+ | Exit; | ||
+ | end; | ||
+ | |||
+ | Escritorio := Servidor.CreateInstance('com.sun.star.frame.Desktop'); | ||
− | + | ParametrosCarga := VarArrayCreate([0, -1], varVariant); | |
− | + | {Crear un documento nuevo} | |
+ | Documento := Escritorio.LoadComponentFromURL('private:factory/swriter', | ||
+ | '_blank', 0, ParametrosCarga); | ||
− | + | CursorTexto := Documento.Text.CreateTextCursor; | |
− | |||
− | |||
− | + | {Insertarun documento existente} //Substituye por tu ruta y documento | |
+ | CursorTexto.InsertDocumentFromURL('file:///C|/mi/ruta/midocumento.doc', | ||
+ | ParametrosCarga); | ||
+ | end.</delphi> | ||
− | + | Y aquí un ejemplo sencillo de cómo abrir un documento con tu programa usando el servidor de automatización de Word. Ten en cuenta que este ejemplo sólo funciona en Windows y sólo cuando se compila con Delphi; Free Pascal 2.2.2 compila el código, pero no funciona. Por favor. Comprueba más adelante o prueba con una versión más reciente de FPC. | |
− | |||
− | |||
− | |||
− | |||
− | + | <delphi> program PruebaMsOffice; | |
− | < | ||
− | program | ||
− | {$IFDEF FPC} | + | {$IFDEF FPC} |
− | + | {$MODE Delphi} | |
− | {$ELSE} | + | {$ELSE} |
− | + | {$APPTYPE CONSOLE} | |
− | {$ENDIF} | + | {$ENDIF} |
− | uses | + | uses |
− | + | SysUtils, Variants, ComObj; | |
− | const | + | const |
− | + | NombreServidor = 'Word.Application'; | |
− | var | + | var |
− | + | Servidor : Variant; | |
− | begin | + | begin |
− | + | if Assigned(InitProc) then | |
− | + | TProcedure(InitProc); | |
− | + | try | |
− | + | Servidor := CreateOleObject(NombreServidor); | |
− | + | except | |
− | + | WriteLn('No puedo arrancar M$Word.'); | |
Exit; | Exit; | ||
end; | end; | ||
− | { | + | {Abrir un documento existente} //Substituye por tu ruta y documento |
− | + | Servidor.Documents.Open('c:\mi\ruta\midocumento.doc'); | |
− | |||
− | |||
− | + | Servidor.Visible := True; {Hacer Word visible} | |
− | |||
+ | end.</delphi> | ||
== Attempting to use Python to manipulate OpenOffice == | == Attempting to use Python to manipulate OpenOffice == |
Revision as of 21:29, 7 November 2009
│
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):
Ver también el tema más abajo sobre Python.
Usar automatización COM para interactuar con OpenOffice y Microsoft Office
La automatización COM es exclusiva de Windows, asíq que lso ejemplos que siguen no funcionan ni en OS X ni en Linux. Para estas plataformas ver Prescindiendo de la automatización COM de Windows. Si sólo necesita crear y/o ver un documento de texto desde su programa, da un vistazo al XDev Toolkit.
Este es una ejemplo sencillo de cómo abrir un documento con tu programa utilizando el servidor de automatización de OpenOffice. Recuerda que esto sólo funciona en Windows.
<delphi> program PruebaOpenOffice;
{$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}
uses SysUtils, Variants, ComObj;
const NombreServidor = 'com.sun.star.ServiceManager'; var Servidor : Variant; Escritorio : Variant; ParametrosCarga : Variant; Documento : Variant; CursorTexto : Variant; begin if Assigned(InitProc) then TProcedure(InitProc);
try Servidor := CreateOleObject(NombreServidor); except WriteLn('No puedo arrancar OpenOffice.'); Exit; end;
Escritorio := Servidor.CreateInstance('com.sun.star.frame.Desktop');
ParametrosCarga := VarArrayCreate([0, -1], varVariant);
{Crear un documento nuevo} Documento := Escritorio.LoadComponentFromURL('private:factory/swriter', '_blank', 0, ParametrosCarga);
CursorTexto := Documento.Text.CreateTextCursor;
{Insertarun documento existente} //Substituye por tu ruta y documento CursorTexto.InsertDocumentFromURL('file:///C|/mi/ruta/midocumento.doc', ParametrosCarga); end.</delphi>
Y aquí un ejemplo sencillo de cómo abrir un documento con tu programa usando el servidor de automatización de Word. Ten en cuenta que este ejemplo sólo funciona en Windows y sólo cuando se compila con Delphi; Free Pascal 2.2.2 compila el código, pero no funciona. Por favor. Comprueba más adelante o prueba con una versión más reciente de FPC.
<delphi> program PruebaMsOffice;
{$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}
uses SysUtils, Variants, ComObj;
const NombreServidor = 'Word.Application'; var Servidor : Variant; begin if Assigned(InitProc) then TProcedure(InitProc);
try Servidor := CreateOleObject(NombreServidor); except WriteLn('No puedo arrancar M$Word.'); Exit; end;
{Abrir un documento existente} //Substituye por tu ruta y documento Servidor.Documents.Open('c:\mi\ruta\midocumento.doc');
Servidor.Visible := True; {Hacer Word visible}
end.</delphi>
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:
- Test UNO via Python macro run within OO
- Test UNO via Python standalone script
- Support for running Python scripts in Pascal
- Test UNO via Python script run in Pascal
- 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
- Excel file format description on the OpenOffice website
- Traducido por Iskraelectrica