procedure TForm1.Button1Click(Sender: TObject); var i,j:integer; ExcelApp: Variant; begin with ADOQuery1 do begin if not IsEmpty then if SaveDialog1.Execute then begin ExcelApp := CreateOleObject( 'Excel.Application' ); {--打开模块文件--} ExcelApp.WorkBooks.Open( ExtractFilePath(Application.ExeName)+'\ert.xls'); j:=2; {---写数据----} while not eof do begin for i :=0 to FieldCount-1 do ExcelApp.Cells[j,i+1].Value:=Fields[i].AsString; inc(j); next; end; {--另存为---} ExcelApp.activeworkbook.SaveAs(SaveDialog1.FileName); ExcelApp.activeworkbook.close; ExcelApp.quit; end; end; end; 以上代码已经测试.
刚发现在点错,修改一下才行: 顺便解释一下: 本例有一个已写好表头的模块文件(ert.xls)保存在程序目录中,现在要实现将ADOQUERY1的资料写到这个模块文件中去,并且将写好数据的表另存为其它名称的EXCEL文件:procedure TForm1.Button1Click(Sender: TObject); var i,j:integer; ExcelApp: Variant; begin with ADOQuery1 do begin if not IsEmpty then if SaveDialog1.Execute then begin First;{--------------------------补回此句} ExcelApp := CreateOleObject( 'Excel.Application' ); {--打开模块文件--} ExcelApp.WorkBooks.Open( ExtractFilePath(Application.ExeName)+'\ert.xls'); j:=2;{表头为第一行,那么数据写入的开始行就为第二行} while not eof do begin for i :=0 to FieldCount-1 do ExcelApp.Cells[j,i+1].Value:=Fields[i].AsString; inc(j); next; end; {--另存为---} ExcelApp.activeworkbook.SaveAs(SaveDialog1.FileName); ExcelApp.activeworkbook.close; ExcelApp.quit; end; end; end;
拷贝文件:
copyfile(pchar(表头文件.xls'),pchar(待保存文件),true)
procedure TForm1.Button1Click(Sender: TObject);
var
i,j:integer;
ExcelApp: Variant;
begin
with ADOQuery1 do begin
if not IsEmpty then
if SaveDialog1.Execute then begin
ExcelApp := CreateOleObject( 'Excel.Application' );
{--打开模块文件--}
ExcelApp.WorkBooks.Open( ExtractFilePath(Application.ExeName)+'\ert.xls');
j:=2;
{---写数据----}
while not eof do begin
for i :=0 to FieldCount-1 do
ExcelApp.Cells[j,i+1].Value:=Fields[i].AsString;
inc(j);
next;
end;
{--另存为---}
ExcelApp.activeworkbook.SaveAs(SaveDialog1.FileName);
ExcelApp.activeworkbook.close;
ExcelApp.quit;
end;
end;
end;
以上代码已经测试.
ExtractFilePath(Application.ExeName)+'\ert.xls'
意思是名为ert.xls的模块文件是保存在与程序同一目录下
顺便解释一下:
本例有一个已写好表头的模块文件(ert.xls)保存在程序目录中,现在要实现将ADOQUERY1的资料写到这个模块文件中去,并且将写好数据的表另存为其它名称的EXCEL文件:procedure TForm1.Button1Click(Sender: TObject);
var
i,j:integer;
ExcelApp: Variant;
begin
with ADOQuery1 do begin
if not IsEmpty then
if SaveDialog1.Execute then begin
First;{--------------------------补回此句}
ExcelApp := CreateOleObject( 'Excel.Application' );
{--打开模块文件--}
ExcelApp.WorkBooks.Open( ExtractFilePath(Application.ExeName)+'\ert.xls');
j:=2;{表头为第一行,那么数据写入的开始行就为第二行}
while not eof do begin
for i :=0 to FieldCount-1 do
ExcelApp.Cells[j,i+1].Value:=Fields[i].AsString;
inc(j);
next;
end;
{--另存为---}
ExcelApp.activeworkbook.SaveAs(SaveDialog1.FileName);
ExcelApp.activeworkbook.close;
ExcelApp.quit;
end;
end;
end;