procedure ExpDataSetToExcel(Var TheDataSet:TDataSet); var s: TStringList; str: string; i: Integer; ASaveDialog: TSaveDialog; tofileName: string; begin str := ''; tofileName := ''; with TheDataSet do begin DisableControls; try for i := 0 to FieldCount - 1 do str := str + fields[i].DisplayLabel + char(9); str := str + #13; if not IsEmpty then begin First; while not eof do begin for i := 0 to FieldCount - 1 do str := str + Fields[i].AsString + char(9); str := str + #13; next; end; //end while end; finally EnableControls; end; end; s := TStringList.Create; try s.Add(str); ASaveDialog := TSaveDialog.Create(nil); try ASaveDialog.Title := '保存文件'; ASaveDialog.Filter := 'Microsof Excel (*.xls)|*.xls'; if ASaveDialog.Execute then begin tofileName := ASaveDialog.FileName; if pos(uppercase('.xls'), uppercase(tofileName)) = 0 then tofileName := tofileName + '.xls'; if Fileexists(tofileName) then begin if application.MessageBox('文件已存在,确认覆盖?', '提示', mb_okcancel + mb_defbutton1) = idok then begin Deletefile(pchar(tofileName)); s.SaveToFile(tofileName); //保存 application.MessageBox( '数据导出完毕!', '信息', MB_OK + MB_ICONINFORMATION); end; end else begin s.SaveToFile(tofileName); //保存 application.MessageBox('数据导出完毕!', '信息', MB_OK + MB_ICONINFORMATION); end; end; finally FreeAndNil(ASaveDialog); end; finally FreeAndNil(s); end; end; 搜一下很多的!
var
s: TStringList;
str: string;
i: Integer;
ASaveDialog: TSaveDialog;
tofileName: string;
begin
str := '';
tofileName := '';
with TheDataSet do
begin
DisableControls;
try
for i := 0 to FieldCount - 1 do
str := str + fields[i].DisplayLabel + char(9);
str := str + #13;
if not IsEmpty then
begin
First;
while not eof do
begin
for i := 0 to FieldCount - 1 do
str := str + Fields[i].AsString + char(9);
str := str + #13;
next;
end; //end while
end;
finally
EnableControls;
end;
end;
s := TStringList.Create;
try
s.Add(str);
ASaveDialog := TSaveDialog.Create(nil);
try
ASaveDialog.Title := '保存文件';
ASaveDialog.Filter := 'Microsof Excel (*.xls)|*.xls';
if ASaveDialog.Execute then
begin
tofileName := ASaveDialog.FileName;
if pos(uppercase('.xls'), uppercase(tofileName)) = 0 then
tofileName := tofileName + '.xls';
if Fileexists(tofileName) then
begin
if application.MessageBox('文件已存在,确认覆盖?', '提示', mb_okcancel + mb_defbutton1) = idok then
begin
Deletefile(pchar(tofileName));
s.SaveToFile(tofileName); //保存
application.MessageBox( '数据导出完毕!', '信息', MB_OK + MB_ICONINFORMATION);
end;
end
else
begin
s.SaveToFile(tofileName); //保存
application.MessageBox('数据导出完毕!', '信息', MB_OK + MB_ICONINFORMATION);
end;
end;
finally
FreeAndNil(ASaveDialog);
end;
finally
FreeAndNil(s);
end;
end;
搜一下很多的!
ExpDataSetToExcel(DBGrid.DataSource.DataSet)