转贴:导出数据库中数据到EXCEL文件中的代码, 把adoquery1 改成你对应的dbgrid的dataset就可以了 uses comobj; 定义一个常量 const xlCSV = 6; //不定义这个excelapp的saveas用不了 var ExcelApp: Variant; temp_string:array[0..20] of string; f:textfile; fs,str,tempclass:string; i,j:integer; adoquery1:tadoquery; begin if exportsavedialog.execute then begin fs:=exportsavedialog.filename;
for i:=0 to 20 do temp_string[i]:=''; ExcelApp := CreateOleObject( 'Excel.Application' ); ExcelApp.Visible := True; ExcelApp.Caption := '应用程序调用 Microsoft Excel'; ExcelApp.WorkBooks.Add; ExcelApp.WorkSheets[1].Activate; adoquery1:=Tadoquery.Create(nil); adoquery1.Connection:=custadoconnection; adoquery1.SQL.Clear; adoquery1.SQL.Add('select * from custdetails'); adoquery1.Open; if adoquery1.RecordCount > 0 then begin with adoquery1 do begin first; j:=1; while NOT EOF do begin for i:=1 to adoquery1.FieldCount-1 do begin excelapp.cells[j,i].value:=adoquery1.Fields[i].AsString; end; next; j:=j+1; end; end; end; ExcelApp.activeworkbook.Saveas(fs); ExcelApp.WorkBooks.Close; ExcelApp.Quit; end; end; end;
http://expert.csdn.net/Expert/topic/1887/1887707.xml?temp=.1997492
http://expert.csdn.net/Expert/topic/1855/1855520.xml?temp=.785885
把adoquery1 改成你对应的dbgrid的dataset就可以了
uses comobj;
定义一个常量
const xlCSV = 6; //不定义这个excelapp的saveas用不了
var
ExcelApp: Variant;
temp_string:array[0..20] of string;
f:textfile;
fs,str,tempclass:string;
i,j:integer;
adoquery1:tadoquery;
begin
if exportsavedialog.execute then
begin
fs:=exportsavedialog.filename;
for i:=0 to 20 do temp_string[i]:='';
ExcelApp := CreateOleObject( 'Excel.Application' );
ExcelApp.Visible := True;
ExcelApp.Caption := '应用程序调用 Microsoft Excel';
ExcelApp.WorkBooks.Add;
ExcelApp.WorkSheets[1].Activate; adoquery1:=Tadoquery.Create(nil);
adoquery1.Connection:=custadoconnection;
adoquery1.SQL.Clear;
adoquery1.SQL.Add('select * from custdetails');
adoquery1.Open;
if adoquery1.RecordCount > 0 then
begin
with adoquery1 do
begin
first;
j:=1;
while NOT EOF do
begin
for i:=1 to adoquery1.FieldCount-1 do
begin
excelapp.cells[j,i].value:=adoquery1.Fields[i].AsString;
end;
next;
j:=j+1;
end;
end;
end;
ExcelApp.activeworkbook.Saveas(fs);
ExcelApp.WorkBooks.Close;
ExcelApp.Quit;
end;
end;
end;