Difference between revisions of "Office Automation"

From Lazarus wiki
Jump to navigationJump to search
(→‎Using COM Automation to interact with OpenOffice and Microsoft Office: Link to impressive Excel automation example page)
m (→‎See also: Added Powerpoint automation link)
(17 intermediate revisions by 10 users not shown)
Line 1: Line 1:
 +
{{Platform only|Windows|Windows|Windows}}
 
{{Office Automation}}
 
{{Office Automation}}
  
The ability to interact with office software and generate spreadsheets, text documents and presentations from code can be invaluable in the office, and win a lot of time for those that can do it. One example of this is the creation of applications that can read files in an arbitrary format and output an Excel file, a task much more efficient to be done with code then manually.
+
The ability to interact with Office software and generate spreadsheets, text documents and presentations from code can be invaluable in the office, and save a lot of time otherwise spent on repetitive tasks.  
 +
 
 +
One example of this is the creation of applications that can read files in an arbitrary format and output an Excel file, a task that can be done much more efficiently with code than manually.
  
 
== Using the OpenOffice UNO Bridge ==
 
== Using the OpenOffice UNO Bridge ==
Line 9: Line 12:
  
 
[http://wiki.services.openoffice.org/wiki/Uno/Article/About_Bridges About Bridges]
 
[http://wiki.services.openoffice.org/wiki/Uno/Article/About_Bridges About Bridges]
 
See also the topic below about Python.
 
  
 
== Using COM Automation to interact with OpenOffice and Microsoft Office==
 
== Using COM Automation to interact with OpenOffice and 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  [http://wiki.lazarus.freepascal.org/Multiplatform_Programming_Guide#Making_do_without_Windows_COM_Automation 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 [http://web.fastermac.net/~MacPgmr/XDev/XDevStatus.html#RTF XDev Toolkit].
+
Automation is unique to Windows so the following two examples won't work on OS X or Linux. For those platforms, please refer to  [http://wiki.lazarus.freepascal.org/Multiplatform_Programming_Guide#Making_do_without_Windows_COM_Automation 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]].
  
 +
=== OpenOffice/LibreOffice on Windows ===
 
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.
 
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.
  
<syntaxhighlight>program TestOO;
+
<syntaxhighlight lang=pascal>
 +
program TestOO;
  
 
{$IFDEF FPC}
 
{$IFDEF FPC}
Line 52: Line 55:
  
 
   {Create new document}
 
   {Create new document}
   Document := Desktop.LoadComponentFromURL('private:factory/swriter',
+
   Document := Desktop.LoadComponentFromURL('private:factory/swriter', '_blank', 0, LoadParams);
                                          '_blank', 0, LoadParams);
+
 
 +
  {or Open existing} //you must use forward slashes, not backward!
 +
  //Document := Desktop.LoadComponentFromURL('file:///C:/my/path/mydoc.doc', '_blank', 0, LoadParams);  
  
 
   TextCursor := Document.Text.CreateTextCursor;
 
   TextCursor := Document.Text.CreateTextCursor;
  
 
   {Insert existing document}  //Substitute your path and doc
 
   {Insert existing document}  //Substitute your path and doc
   TextCursor.InsertDocumentFromURL('file:///C|/my/path/mydoc.doc',
+
   TextCursor.InsertDocumentFromURL('file:///C:/my/path/mydoc.doc', LoadParams);
                                  LoadParams);
 
 
end.</syntaxhighlight>
 
end.</syntaxhighlight>
  
 +
More comprehensive examples can found [https://bitbucket.org/blikblum/pascal-demos/src/04a4d10bf30b59215ff3ad4cd41dba71405ae5fc/fpc/LibreOfficeOLE/?at=master here]:
 +
* OLECreateTextDoc: Create and populate a text document with paragraph, table and frame
 +
* OLEEditTextDoc: Load an existing text document, search with regular expression, replace text and add rows to a table
 +
 +
=== Office on Windows ===
 
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. This will work with both delphi and fpc.
 
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. This will work with both delphi and fpc.
  
<syntaxhighlight>program TestMsOffice;
+
<syntaxhighlight lang=pascal>
 +
program TestMsOffice;
  
 
{$IFDEF FPC}
 
{$IFDEF FPC}
Line 79: Line 89:
 
var
 
var
 
   Server    : Variant;
 
   Server    : Variant;
 +
  w:widestring;
 
begin
 
begin
 
   if Assigned(InitProc) then
 
   if Assigned(InitProc) then
Line 91: Line 102:
  
 
   {Open existing document}  //Substitute your path and doc
 
   {Open existing document}  //Substitute your path and doc
   Server.Documents.Open('c:\my\path\mydoc.doc');  
+
   w:= UTF8Decode('c:\my\path\mydoc.doc');
 
+
  Server.Documents.Open(w); //OLE uses BSTR (http://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx). Only widestring is compatible with BSTR in FPC, so conversion is needed for nonlatin chars.
 
   Server.Visible := True;  {Make Word visible}
 
   Server.Visible := True;  {Make Word visible}
  
 
end.</syntaxhighlight>
 
end.</syntaxhighlight>
  
A lot of examples for Excel are available on the German wiki page [[ExcelAutomation/de]].
 
  
== Attempting to use Python to manipulate OpenOffice ==
+
Here is a sample code how to work in an open Word document, using the Word Automation server.
  
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:
+
<syntaxhighlight lang=pascal>
 
+
var
 
+
  Server: Variant;
# Test UNO via Python macro run within OO
+
begin
# Test UNO via Python standalone script
+
  try
# Support for running Python scripts in Pascal
+
    Server := GetActiveOleObject('Word.Application');
# Test UNO via Python script run in Pascal
+
  except
# Pascal class that wraps Python UNO
+
    try
 
+
      ShowMessage('Word not already open create a Word Object');
 
+
      // If no instance of Word is running, try to Create a new Word Object
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).
+
      Server := CreateOleObject('Word.Application');
 
+
    except
==== Step 1. Test UNO via Python macro run within OO ====
+
      ShowMessage('Cannot start Word/Word not installed ?');
 
+
      Exit;
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:
+
    end;
 
+
   end;
<pre>C:\Document and Setting\<username>\Application Data\OpenOffice.org2\user\Scripts\python\Library1</pre>
+
end; 
 
 
On Mac OS X, this folder is:
 
 
 
<pre>~/Library/Preferences/NeoOffice-2.2/user/Scripts/python/Library1</pre>
 
 
 
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:
 
 
 
<syntaxhighlight lang="python"># 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)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
In OO, choose Tools | Macros | Organize Macros | Python and run the macro to make sure it works.
+
Limitations:
 
+
Since '''End''' is a reserved word in FPC it shall be used as a parameter after the ''&'' sign.
==== Step 2. Test UNO via Python standalone script ====
 
 
 
Here is the same code as a standalone script:
 
  
<syntaxhighlight lang="python"># Python script that tests UNO by creating new document and inserting some text.
+
<syntaxhighlight lang=pascal>
 
+
Server.ActiveDocument.Application.Selection.start:=Server.ActiveDocument.Application.Selection.&end+1;
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)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
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.
 
  
<pre>"\program files\openoffice.org 2.3\program\python" test.py</pre>
+
A lot of examples for Excel are available on the German wiki page [[ExcelAutomation/de]].
 
 
On Mac OS X, run the script like this from a Terminal window:
 
 
 
<syntaxhighlight lang="bash">#!/bin/sh
 
export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH":/Applications/NeoOffice.app/Contents/MacOS"
 
python2.3 test.py</syntaxhighlight>
 
 
 
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 fpXMLXSDExport unit ==
 
== Using the fpXMLXSDExport unit ==
FPC 2.6 and newer contain the '''fpXMLXSDExport''' unit, part of the FCL-DB export components. With that, you can export to various XML formats, including a Microsoft Access-compatible format and a Microsoft Excel-compatible format.
+
FPC 2.6 and newer contain the '''fpXMLXSDExport''' unit, part of the FCL-DB export components. With that, you can export datasets to various XML formats, including a Microsoft Access-compatible format and a Microsoft Excel-compatible format.
  
 
The Access format can output XML with or without an embedded XSD data/table definition. Note that exporting binary/BLOB type data needs additional action at the Access import end, as Access does not support proper binary fields, only OLE fields.
 
The Access format can output XML with or without an embedded XSD data/table definition. Note that exporting binary/BLOB type data needs additional action at the Access import end, as Access does not support proper binary fields, only OLE fields.
Line 196: Line 147:
 
In the Excel format, multiline text fields are not supported at the moment: the line ends are removed during the export.
 
In the Excel format, multiline text fields are not supported at the moment: the line ends are removed during the export.
  
Lazarus (e.g. Lazarus 1.0) provides a visual component for this: after installing the '''lazdbexport''' package, you will see the '''TXMLXSDExporter''' component on the '''Data Export''' tab
+
Lazarus provides a visual component for this: after installing the '''lazdbexport''' package, you will see the '''TXMLXSDExporter''' component on the '''Data Export''' tab
  
 
See [[fpXMLXSDExport]] for details.
 
See [[fpXMLXSDExport]] for details.
  
== Using the Free Pascal Spreadsheet Library ==
+
== Using the FPSpreadsheet 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.
 
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.
  
The advantages are that fpspreadsheet is 100% ObjectPascal code, and it requires no external libraries or programs.
+
The advantages are that fpspreadsheet is 100% [[Object Pascal]] code, and it requires no external libraries or programs.
  
 
== Writing an Excel file using ADO ==
 
== Writing an Excel file using ADO ==
Line 224: Line 175:
  
 
Example - Open/Read Excel file:
 
Example - Open/Read Excel file:
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang=pascal>
 
uses .....  comobj;
 
uses .....  comobj;
  
Line 255: Line 207:
 
If you want to make some changes and you want them to write back into the Excel, file you can use:
 
If you want to make some changes and you want them to write back into the Excel, file you can use:
  
<syntaxhighlight>
+
<syntaxhighlight lang=pascal>
 
XLApp.Cells[x,y].Value := SG.Cells[y,x];
 
XLApp.Cells[x,y].Value := SG.Cells[y,x];
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
If you want to save:
 
If you want to save:
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang=pascal>
 
XLApp.ActiveWorkBook.Save;
 
XLApp.ActiveWorkBook.Save;
 
</syntaxhighlight>
 
</syntaxhighlight>
Line 268: Line 221:
 
The component provides a library interface, abstracting the Excel COM and the Calc Open Office UNO interfaces.
 
The component provides a library interface, abstracting the Excel COM and the Calc Open Office UNO interfaces.
 
The component is available here:
 
The component is available here:
http://www.tcoq.org/composants
+
http://tcoq.free.fr/composants.html (Link verified in May 2016)
  
 
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.
 
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.
 
Be careful, this is a work-in-progress. Use it at your own risk.
 
Be careful, this is a work-in-progress. Use it at your own risk.
  
Functionality:
+
'''Functionality:'''
  
 
* creating and loading excel workbooks,
 
* creating and loading excel workbooks,
Line 287: Line 240:
 
'''Inits first.'''
 
'''Inits first.'''
  
<syntaxhighlight> IMPLEMENTATION
+
<syntaxhighlight lang=pascal>
 +
  IMPLEMENTATION
 
   USES
 
   USES
 
     ExcelUtilities,
 
     ExcelUtilities,
Line 303: Line 257:
  
 
Getting a sheet is simple:
 
Getting a sheet is simple:
<syntaxhighlight> // Initializing the common excel workbook:
+
 
 +
<syntaxhighlight lang=pascal>
 +
  // Initializing the common excel workbook:
 
   ExcelApp        := TExcelApplication.Create(nil) ;
 
   ExcelApp        := TExcelApplication.Create(nil) ;
 
   ExcelApp.Active  := True ;
 
   ExcelApp.Active  := True ;
Line 314: Line 270:
  
 
Playing around with cells is simple too:
 
Playing around with cells is simple too:
<syntaxhighlight> // adding a value
+
 
 +
<syntaxhighlight lang=pascal>
 +
  // adding a value
 
   aCell := ExcelSheet.Cells(1, 1) ;
 
   aCell := ExcelSheet.Cells(1, 1) ;
 
   aCell.Value := 10;
 
   aCell.Value := 10;
Line 330: Line 288:
 
==Copy HTML to the clipboard==
 
==Copy HTML to the clipboard==
  
You can copy HTML to the clipboard which is understood by many applications. This way you can copy formatted text. For those applications that only understand text put plain text too.
+
<p>You can copy HTML to the clipboard which is understood by many applications. This way you can copy formatted text. For those applications that only understand text put plain text too.</p>
 +
<p>Microsoft Office applications require HTML to be pasted onto the clipboard in a more complex format than described here.  [[Clipboard#Windows|See here for an example that works with Microsoft Office.]]</p>
  
<syntaxhighlight>uses
+
 
 +
<syntaxhighlight lang=pascal>
 +
uses
 
   ClipBrd;
 
   ClipBrd;
 
...
 
...
Line 338: Line 299:
 
   ClipbrdFmtHTML:=RegisterClipboardFormat('text/html');
 
   ClipbrdFmtHTML:=RegisterClipboardFormat('text/html');
 
...
 
...
 +
  // Clear any previous formats off the clipboard before starting
 +
  Clipboard.Clear;
 +
 
   // put text and html on the clipboard. Other applications will choose the best format automatically.
 
   // put text and html on the clipboard. Other applications will choose the best format automatically.
 
   ThePlainUTF8Text:='Simple text';
 
   ThePlainUTF8Text:='Simple text';
 
   Clipboard.AsText:=ThePlainUTF8Text;  
 
   Clipboard.AsText:=ThePlainUTF8Text;  
 +
 
   AsHTML:='<b>Formatted</b> text'; // text with formattings
 
   AsHTML:='<b>Formatted</b> text'; // text with formattings
 
   Clipboard.AddFormat(ClipbrdFmtHTML,AsHTML[1],length(AsHTML));</syntaxhighlight>
 
   Clipboard.AddFormat(ClipbrdFmtHTML,AsHTML[1],length(AsHTML));</syntaxhighlight>
Line 347: Line 312:
  
 
* [[Clipboard]]
 
* [[Clipboard]]
 +
* [[PowerpointAutomation/de|Powerpoint Automation]]
  
 
== External links ==
 
== External links ==
  
 
* [http://sc.openoffice.org/excelfileformat.pdf Excel file format] - description on OpenOffice website
 
* [http://sc.openoffice.org/excelfileformat.pdf Excel file format] - description on OpenOffice website
 
[[Category:Tutorials]]
 

Revision as of 08:53, 23 February 2020

Windows logo - 2012.svg

This article applies to Windows only.

See also: Multiplatform Programming Guide

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

The ability to interact with Office software and generate spreadsheets, text documents and presentations from code can be invaluable in the office, and save a lot of time otherwise spent on repetitive tasks.

One example of this is the creation of applications that can read files in an arbitrary format and output an Excel file, a task that can be done much more efficiently with code than manually.

Using the OpenOffice UNO Bridge

OpenOffice has language bindings for C++, Java, JavaScript and Python. On Windows, OpenOffice can also be manipulated in Pascal via COM Automation (see below), but there is currently no easy way of using OpenOffice's UNO (Universal Network Objects) from Pascal on OS X and Linux. If you're interested in developing an OO "bridge" for Pascal, please refer to these links for more information (caution: these links are quite techie in true Sun fashion):

api.openoffice.org

About Bridges

Using COM Automation to interact with OpenOffice and 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.

OpenOffice/LibreOffice on Windows

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);

   {or Open existing} //you must use forward slashes, not backward!
  //Document := Desktop.LoadComponentFromURL('file:///C:/my/path/mydoc.doc', '_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.

More comprehensive examples can found here:

  • OLECreateTextDoc: Create and populate a text document with paragraph, table and frame
  • OLEEditTextDoc: Load an existing text document, search with regular expression, replace text and add rows to a table

Office on Windows

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. This will work with both delphi and fpc.

program TestMsOffice;

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

uses
  SysUtils, Variants, ComObj;

const
  ServerName = 'Word.Application';
var
  Server     : Variant;
  w:widestring;
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
  w:= UTF8Decode('c:\my\path\mydoc.doc');
  Server.Documents.Open(w); //OLE uses BSTR (http://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx). Only widestring is compatible with BSTR in FPC, so conversion is needed for nonlatin chars.
  Server.Visible := True;  {Make Word visible}

end.


Here is a sample code how to work in an open Word document, using the Word Automation server.

var
  Server: Variant;
begin
  try
    Server := GetActiveOleObject('Word.Application');
  except
    try
      ShowMessage('Word not already open create a Word Object');
      // If no instance of Word is running, try to Create a new Word Object
      Server := CreateOleObject('Word.Application');
    except
      ShowMessage('Cannot start Word/Word not installed ?');
      Exit;
    end;
  end;
end;

Limitations: Since End is a reserved word in FPC it shall be used as a parameter after the & sign.

Server.ActiveDocument.Application.Selection.start:=Server.ActiveDocument.Application.Selection.&end+1;


A lot of examples for Excel are available on the German wiki page ExcelAutomation/de.

Using the fpXMLXSDExport unit

FPC 2.6 and newer contain the fpXMLXSDExport unit, part of the FCL-DB export components. With that, you can export datasets to various XML formats, including a Microsoft Access-compatible format and a Microsoft Excel-compatible format.

The Access format can output XML with or without an embedded XSD data/table definition. Note that exporting binary/BLOB type data needs additional action at the Access import end, as Access does not support proper binary fields, only OLE fields.

In the Excel format, multiline text fields are not supported at the moment: the line ends are removed during the export.

Lazarus provides a visual component for this: after installing the lazdbexport package, you will see the TXMLXSDExporter component on the Data Export tab

See fpXMLXSDExport for details.

Using the FPSpreadsheet 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.

The advantages are that fpspreadsheet is 100% Object Pascal code, and it requires no external libraries or programs.

Writing an Excel file using ADO

please write me.

Reading/Writing an Excel file using OLE

This method needs Excel to be installed on the user's machine because it uses OLE to access it.

Keep in mind that this method starts Excel in the background, which opens the file and works with it like a real user.

  • Create a new form with button, stringgrid and edit.
  • Create a new Excel file and fill a few cells.


excel123.png


Example - Open/Read Excel file:

uses .....  comobj;

procedure TForm1.Button1Click(Sender: TObject);

Var   XLApp: OLEVariant;
      x,y: byte;
      path: variant;

begin
 XLApp := CreateOleObject('Excel.Application'); // requires comobj in uses
 try
   XLApp.Visible := False;         // Hide Excel
   XLApp.DisplayAlerts := False;
   path := edit1.Text;
   XLApp.Workbooks.Open(Path);     // Open the Workbook
   for x := 1 to 4 do
    begin
     for y := 1 to 6 do
      begin
       SG.Cells[x,y] := XLApp.Cells[y,x].Value;  // fill stringgrid with values
      end;
    end;
 finally
   XLApp.Quit;
   XLAPP := Unassigned;
  end;

If you want to make some changes and you want them to write back into the Excel, file you can use:

XLApp.Cells[x,y].Value := SG.Cells[y,x];

If you want to save:

XLApp.ActiveWorkBook.Save;

Read/Writing an Excel file using the SpreadSheet Interface Component

The component provides a library interface, abstracting the Excel COM and the Calc Open Office UNO interfaces. The component is available here: http://tcoq.free.fr/composants.html (Link verified in May 2016)

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. Be careful, this is a work-in-progress. Use it at your own risk.

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.

Inits first.

  IMPLEMENTATION
  USES
    ExcelUtilities,
    SpreadSheetInterfaces ;

  VAR
   aCell    : IRange ;
   aValue   : OleVariant ; // Not sure about this, but it works. ie( Edit.Text := STRING(aValue); )
   ExcelApp : TExcelApplication ;
   ExcelWbs : IWorkBooks ;

  ExcelBook   : IWorkBook ;
  ExcelSheet  : ISheet ;
  ExcelSheets : ISheets ;

Getting a sheet is simple:

  // Initializing the common excel workbook:
  ExcelApp         := TExcelApplication.Create(nil) ;
  ExcelApp.Active  := True ;
  ExcelApp.Visible := True ;

  ExcelWbs    := ExcelApp.WorkBooks ;
  ExcelBook   := ExcelWbs.Add ;
  ExcelSheets := ExcelBook.Sheets ;
  ExcelSheet  := ExcelSheets.Sheet(1) ;

Playing around with cells is simple too:

  // adding a value
  aCell := ExcelSheet.Cells(1, 1) ;
  aCell.Value := 10;

  // adding a formula
  aCell := ExcelSheet.Cells(2,1) ;
  aCell.Formula := '=A1+10' ;

  // getting the value computed in Excel
  aValue := aCell.Value ;


The test case provided has many more examples.

Copy HTML to the clipboard

You can copy HTML to the clipboard which is understood by many applications. This way you can copy formatted text. For those applications that only understand text put plain text too.

Microsoft Office applications require HTML to be pasted onto the clipboard in a more complex format than described here. See here for an example that works with Microsoft Office.


uses
  ClipBrd;
...
  // register the mime type for text/html. You can do this once at program start:
  ClipbrdFmtHTML:=RegisterClipboardFormat('text/html');
...
  // Clear any previous formats off the clipboard before starting
  Clipboard.Clear;

  // put text and html on the clipboard. Other applications will choose the best format automatically.
  ThePlainUTF8Text:='Simple text';
  Clipboard.AsText:=ThePlainUTF8Text; 

  AsHTML:='<b>Formatted</b> text'; // text with formattings
  Clipboard.AddFormat(ClipbrdFmtHTML,AsHTML[1],length(AsHTML));

See also

External links