Office Automation/zh CN
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) │
与 Office 办公软件交互,从代码中生成电子表格,文本文档及幻灯片的能力对办公来说是非常有价值的,可以节省大量时间避免做重复任务。
这样的一种例子是建立一可以读取任意格式文件的程序,并输出为一 Excel 文档,这项任务使用代码完成远比手工完成高效地多。
使用 OpenOffice UNO 桥
OpenOffice 有针对 C++, Java, JavaScript 和 Python 的语言绑定件。在 Windows 平台上,OpenOffice 也可通过 COM 自动化使用 Pascal 操纵(见下文),但目前在 OS X 和 Linux 上使用 Pascal 操纵 OpenOffice 的 UNO (通用网络对象)并不那么容易。 如果您对使用 Pascal 开发面向对象的”桥“感兴趣,请参看如下联接以获取更多信息。(注意:以下连接特别具有 Sun 专业范儿)
使用 COM 自动化与 OpenOffice 和 Microsoft Office 交互
自动化是 Windows 特有的所以以下两个事例不能在 OS X 或 Linux 上运行. 对于后两者请参见 Making do without Windows COM Automation. 如果您只是想在您的程序中创建或查看文字处理文档,参看以下联接 XDev Toolkit.
Windows 上的 OpenOffice
以下是简单示例,展示了如何使用 OpenOffice 自动化服务器打开一文档。注意该示例仅可在 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.
Windows 上的 Office
以下是简单示例,展示了如何在您的程序中使用 Word 自动化服务器打开一文档。注意该示例仅可在 Windows 下运行。可在 Delphi 和 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.
以下是展示如何使用Word自动化服务器创建一Word文档对象
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;
限制: 因为 End 是FPC中的保留字,在&号后应被用做参数。
Server.ActiveDocument.Application.Selection.start:=Server.ActiveDocument.Application.Selection.&end+1;
许多Excel的示例可参见该主题的德语Wiki页面 ExcelAutomation/de.
使用 fpXMLXSDExport 单元
FPC 2.6及更新的版本包含fpXMLXSDExport单元,它是FCL-DB导出组件的一部分。有了它您就可以导出数据集合到各种XML格式,包括Microsoft Access兼容格式和Excel兼容格式。
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.
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
- Excel file format - description on OpenOffice website