关于 word 的对象使用可查看 msoffice/office/VbaWrd.hlp,下面是我的一个例子,
里面含有对 Word 操作的常用方法:定位替换、表格等。
procedure TForm1.Button1Click(Sender: TObject);
var WordApp,MyDoc,wTable: OLEVariant;
FileName: string;
i: integer;
procedure FillRow(wTable: OLEVariant; Row,StartColumn: Byte; ss: array of String);
var j: word;
begin
for j := Low(ss) to High(ss) do begin
wTable.Cell(Row,j+StartColumn).Range.Text := ss[j];
end;
end;
begin
FileName := ExtractFileDir(Application.ExeName) + '/test1.dot';
if not FileExists(FileName) then
raise Exception.Create('找不到模板!');
try
WordApp := CreateOleObject('Word.Application');
MyDoc := CreateOleObject('Word.Document');
except
Raise Exception.Create('无法打开Word,请确认已安装Word。');
end;
WordApp.Visible := true;
MyDoc := WordApp.Documents.Add(FileName,false);
MyDoc.BookMarks.Item('表名1').Select;
WordApp.Selection.Text := 'Animals';
wTable := MyDoc.Tables.Item(1);
table1.First;
for i := 2 to 4 do begin
if not Table1.Eof then begin
FillCell(i,1,wtable,'Name');
FillCell(i,2,wtable,'Size');
FillCell(i,3,wtable,'Area');
Table1.Next
end else Break
end;
wTable := MyDoc.Tables.Item(2);
table1.First;
for i := 1 to 3 do
if not table1.Eof then begin
FillRow(wTable,i,2,[table1.fieldbyName('Name').AsString,
table1.FieldByName('Size').AsString,
table1.FieldByName('Area').AsString]);
table1.Next
end;
MyDoc.Tables.Add(MyDoc.Bookmarks.Item('表格3').Range,2,5)
end;
procedure TForm1.FillCell(i, j: byte; wTable: Variant; FieldName: String);
begin
wTable.Cell(i,j).Range.Text := table1.FieldByName(FieldName).AsString
end;