Sign in Join
Wiki copytemporary

Office Automation/it: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11*(Windows only)*
22
33La capacità di interagire con i software di Office per generare fogli di calcolo, documenti di testo, presentazioni da programma costituisce un aiuto incalcolabile negli ambienti di lavoro e può far risparmiare molto tempo specialmente in operazioni ripetitive.
44
55Una tipica applicazione è quella di trasformare files in formato arbitrario in file di Excel, operazione realizzabile in modo molto più efficiente attraverso la programmazione.
66
77## Usare l'interfaccia UNO Bridge di OpenOffice
88
99OpenOffice ha interfacce di programmazione per C++, Java, JavaScript e Python. Su Windows, OpenOffice può essere manipolato anche in Pascal mediante l'Automazione COM (vedi sotto), ma attualmente non vi è un modo semplice di usare il protocollo UNO (Universal Network Objects) da Pascal su OS X e Linux. Se si è interessati a sviluppare un collegamento per OO per il Pascal, si può far riferimento a questi link:
1010
1111[api.openoffice.org](http://api.openoffice.org/)
1212
1313[About Bridges](http://wiki.services.openoffice.org/wiki/Uno/Article/About_Bridges)
1414
1515## Usare l'Automazione COM per interagire con OpenOffice e Microsoft Office
1616
1717L'Automazione tramite COM (Component Object Model) è unica di Windows, quindi i seguenti due esempi non funzionano su OS X e Linux. Per queste piattaforme si faccia riferimento a [Making do without Windows COM Automation](http://wiki.lazarus.freepascal.org/Multiplatform_Programming_Guide#Making_do_without_Windows_COM_Automation). Se si ha bisogno di programmare solo documenti di word processing, si veda [XDev Toolkit](http://web.fastermac.net/~MacPgmr/XDev/XDevStatus.html#RTF).
1818
1919### OpenOffice su Windows
2020
2121Ecco un esempio di come aprire un documento da programma usando il server di Automazione di OpenOffice (solo su Windows).
2222
2323``` pascal
2424program TestOO;
2525
2626{$IFDEF FPC}
2727 {$MODE Delphi}
2828{$ELSE}
2929 {$APPTYPE CONSOLE}
3030{$ENDIF}
3131
3232uses
3333 SysUtils, Variants, ComObj;
3434
3535const
3636 ServerName = 'com.sun.star.ServiceManager';
3737var
3838 Server : Variant;
3939 Desktop : Variant;
4040 LoadParams : Variant;
4141 Document : Variant;
4242 TextCursor : Variant;
4343begin
4444 if Assigned(InitProc) then
4545 TProcedure(InitProc);
4646
4747 try
4848 Server := CreateOleObject(ServerName);
4949 except
5050 WriteLn('Unable to start OO.');
5151 Exit;
5252 end;
5353
5454 Desktop := Server.CreateInstance('com.sun.star.frame.Desktop');
5555
5656 LoadParams := VarArrayCreate([0, -1], varVariant);
5757
5858 {Create new document}
5959 Document := Desktop.LoadComponentFromURL('private:factory/swriter', '_blank', 0, LoadParams);
6060
6161 {or Open existing} //you must use forward slashes, not backward!
6262 //Document := Desktop.LoadComponentFromURL('file:///C:/my/path/mydoc.doc', '_blank', 0, LoadParams);
6363
6464 TextCursor := Document.Text.CreateTextCursor;
6565
6666 {Insert existing document} //Substitute your path and doc
6767 TextCursor.InsertDocumentFromURL('file:///C:/my/path/mydoc.doc', LoadParams);
6868end.
6969```
7070
7171### Office su Windows
7272
7373Ecco un esempio di come aprire un documento da programma usando il server di Automazione di Word (solo su Windows). L'esempio funziona sia in delphi che in fpc.
7474
7575``` pascal
7676program TestMsOffice;
7777
7878{$IFDEF FPC}
7979 {$MODE Delphi}
8080{$ELSE}
8181 {$APPTYPE CONSOLE}
8282{$ENDIF}
8383
8484uses
8585 SysUtils, Variants, ComObj;
8686
8787const
8888 ServerName = 'Word.Application';
8989var
9090 Server : Variant;
9191 w:widestring;
9292begin
9393 if Assigned(InitProc) then
9494 TProcedure(InitProc);
9595
9696 try
9797 Server := CreateOleObject(ServerName);
9898 except
9999 WriteLn('Unable to start Word.');
100100 Exit;
101101 end;
102102
103103 {Open existing document} //Substitute your path and doc
104104 w:= UTF8Decode('c:\my\path\mydoc.doc');
105105 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.
106106 Server.Visible := True; {Make Word visible}
107107
108108end.
109109```
110110
111111Here is a sample code how to work in an open Word document, using the Word Automation server.
112112
113113``` pascal
114114var
115115 Server: Variant;
116116begin
117117 try
118118 Server := GetActiveOleObject('Word.Application');
119119 except
120120 try
121121 ShowMessage('Word not already open create a Word Object');
122122 // If no instance of Word is running, try to Create a new Word Object
123123 Server := CreateOleObject('Word.Application');
124124 except
125125 ShowMessage('Cannot start Word/Word not installed ?');
126126 Exit;
127127 end;
128128 end;
129129end;
130130```
131131
132132Limitations: Since **End** is a reserved word in FPC it shall be used as a parameter after the *&* sign.
133133
134134``` pascal
135135Server.ActiveDocument.Application.Selection.start:=Server.ActiveDocument.Application.Selection.&end+1;
136136```
137137
138138A lot of examples for Excel are available on the German wiki page [[ExcelAutomation/de]].
139139
140140## Using the fpXMLXSDExport unit
141141
142142FPC 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.
143143
144144The 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.
145145
146146In the Excel format, multiline text fields are not supported at the moment: the line ends are removed during the export.
147147
148148Lazarus provides a visual component for this: after installing the **lazdbexport** package, you will see the **TXMLXSDExporter** component on the **Data Export** tab
149149
150150See [[fpXMLXSDExport]] for details.
151151
152152## Using the FPSpreadsheet Library
153153
154154Another 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.
155155
156156The advantages are that fpspreadsheet is 100% [[Object Pascal]] code, and it requires no external libraries or programs.
157157
158158## Writing an Excel file using ADO
159159
160160please write me.
161161
162162## Reading/Writing an Excel file using OLE
163163
164164This method needs Excel to be installed on the user's machine because it uses OLE to access it.
165165
166166***Keep in mind that this method starts Excel in the background, which opens the file and works with it like a real user.***
167167
168168- Create a new form with button, stringgrid and edit.
169169- Create a new Excel file and fill a few cells.
170170
171-<figure>
172-<img src="excel123.png" title="excel123.png" />
173-<figcaption>excel123.png</figcaption>
174-</figure>
171+![](/wiki-images/7/74/Excel123.png)
175172
176173Example - Open/Read Excel file:
177174
178175``` pascal
179176uses ..... comobj;
180177
181178procedure TForm1.Button1Click(Sender: TObject);
182179
183180Var XLApp: OLEVariant;
184181 x,y: byte;
185182 path: variant;
186183
187184begin
188185 XLApp := CreateOleObject('Excel.Application'); // requires comobj in uses
189186 try
190187 XLApp.Visible := False; // Hide Excel
191188 XLApp.DisplayAlerts := False;
192189 path := edit1.Text;
193190 XLApp.Workbooks.Open(Path); // Open the Workbook
194191 for x := 1 to 4 do
195192 begin
196193 for y := 1 to 6 do
197194 begin
198195 SG.Cells[x,y] := XLApp.Cells[y,x].Value; // fill stringgrid with values
199196 end;
200197 end;
201198 finally
202199 XLApp.Quit;
203200 XLAPP := Unassigned;
204201 end;
205202```
206203
207204If you want to make some changes and you want them to write back into the Excel, file you can use:
208205
209206``` pascal
210207XLApp.Cells[x,y].Value := SG.Cells[y,x];
211208```
212209
213210If you want to save:
214211
215212``` pascal
216213XLApp.ActiveWorkBook.Save;
217214```
218215
219216## Read/Writing an Excel file using the SpreadSheet Interface Component
220217
221218The 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)
222219
223220Since 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.
224221
225222**Functionality:**
226223
227224- creating and loading excel workbooks,
228225- saving workbooks,
229226- creating and accessing sheets,
230227- getting values and setting values (and formulas) in cells,
231228- getting and changing color of cells,
232229- getting and changing column height and row width,
233230- creating comments,
234231- creating shapes,
235232- creating charts.
236233
237234**Inits first.**
238235
239236``` pascal
240237 IMPLEMENTATION
241238 USES
242239 ExcelUtilities,
243240 SpreadSheetInterfaces ;
244241
245242 VAR
246243 aCell : IRange ;
247244 aValue : OleVariant ; // Not sure about this, but it works. ie( Edit.Text := STRING(aValue); )
248245 ExcelApp : TExcelApplication ;
249246 ExcelWbs : IWorkBooks ;
250247
251248 ExcelBook : IWorkBook ;
252249 ExcelSheet : ISheet ;
253250 ExcelSheets : ISheets ;
254251```
255252
256253Getting a sheet is simple:
257254
258255``` pascal
259256 // Initializing the common excel workbook:
260257 ExcelApp := TExcelApplication.Create(nil) ;
261258 ExcelApp.Active := True ;
262259 ExcelApp.Visible := True ;
263260
264261 ExcelWbs := ExcelApp.WorkBooks ;
265262 ExcelBook := ExcelWbs.Add ;
266263 ExcelSheets := ExcelBook.Sheets ;
267264 ExcelSheet := ExcelSheets.Sheet(1) ;
268265```
269266
270267Playing around with cells is simple too:
271268
272269``` pascal
273270 // adding a value
274271 aCell := ExcelSheet.Cells(1, 1) ;
275272 aCell.Value := 10;
276273
277274 // adding a formula
278275 aCell := ExcelSheet.Cells(2,1) ;
279276 aCell.Formula := '=A1+10' ;
280277
281278 // getting the value computed in Excel
282279 aValue := aCell.Value ;
283280```
284281
285282The test case provided has many more examples.
286283
287284## Copy HTML to the clipboard
288285
289286You 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.
290287
291288Microsoft Office applications require HTML to be pasted onto the clipboard in a more complex format than described here. [[Clipboard|See here for an example that works with Microsoft Office.]]
292289
293290``` pascal
294291uses
295292 ClipBrd;
296293...
297294 // register the mime type for text/html. You can do this once at program start:
298295 ClipbrdFmtHTML:=RegisterClipboardFormat('text/html');
299296...
300297 // Clear any previous formats off the clipboard before starting
301298 Clipboard.Clear;
302299
303300 // put text and html on the clipboard. Other applications will choose the best format automatically.
304301 ThePlainUTF8Text:='Simple text';
305302 Clipboard.AsText:=ThePlainUTF8Text;
306303
307304 AsHTML:='<b>Formatted</b> text'; // text with formattings
308305 Clipboard.AddFormat(ClipbrdFmtHTML,AsHTML[1],length(AsHTML));
309306```
310307
311308## See also
312309
313310- [[Clipboard]]
314311
315312## External links
316313
317314- [Excel file format](http://sc.openoffice.org/excelfileformat.pdf) - description on OpenOffice website
318315
319316---
320317*From the Free Pascal wiki, page "Office Automation/it", as it stood on 2020-02-21 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history