再来骗点分
其实我以前的贴子全都讲过了。程序也是至少第二次贴。
在填空时,用在 word 文档中的书签来定位;表格则是按表号、行列定位。
//对 Word 的表格进行的操作
//把数据表的内容写入 Word Table
//
unit HandelWord;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,ComObj,
StdCtrls, Db, Grids, DBGrids, DBTables;
type
TForm1 = class(TForm)
Button1: TButton;
Table1: TTable;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure FillCell(i,j: byte; wTable: Variant; FieldName: String);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses word97;
{$R *.DFM}
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);
//操作对齐属性
MyDoc.Paragraphs.Item(1).Alignment := wdAlignParagraphRight;
//表格列宽
Mydoc.Tables.Item(2).Columns.Item(2).Width := 300;
end;
procedure TForm1.FillCell(i, j: byte; wTable: Variant; FieldName: String);
begin
wTable.Cell(i,j).Range.Text := table1.FieldByName(FieldName).AsString
end;
end.