利用StrList的SaveToFile方法实现导出数据到Excel,适用于无格式要求的情况
//实现过程
//DataSet为数据集
//Grid用来取得Excel列标题
//Filename为保存路径及文件名
procedure DatasetToExcel(Dataset:TDataset;Grid:TDBGrid;Filename:String);
var
i:integer;
str:String;
StrList:TStringList;//用于存储数据的字符列表
begin
try
strList:=TStringList.Create;
var
i:integer;
str:String;
StrList:TStringList;//用于存储数据的字符列表
begin
try
strList:=TStringList.Create;
//字段
str:='';
for i:=0 to Dataset.FieldCount-1 do
begin
str:=str+Grid.Columns[i].Title.Caption +#9;
end;
strList.Add(str);
str:='';
for i:=0 to Dataset.FieldCount-1 do
begin
str:=str+Grid.Columns[i].Title.Caption +#9;
end;
strList.Add(str);
with Dataset do
begin
First;//指针至表头
DisableControls;
while not EOF do
begin
str:='';
for i:=0 to FieldCount-1 do
begin
str:=str+VarToStr(Dataset.Fields[i].Value)+#9;
end;
strList.Add(str);
Next;
end;
StrList.SaveToFile(FileName);//存储路径
EnableControls;
end;
finally
StrList.free;//释放内存
end;
end;
begin
First;//指针至表头
DisableControls;
while not EOF do
begin
str:='';
for i:=0 to FieldCount-1 do
begin
str:=str+VarToStr(Dataset.Fields[i].Value)+#9;
end;
strList.Add(str);
Next;
end;
StrList.SaveToFile(FileName);//存储路径
EnableControls;
end;
finally
StrList.free;//释放内存
end;
end;
//调用方法
procedure TAccountQueryFrm.ButtonExportClick(Sender: TObject);
var
SaveDialog:TSaveDialog;
begin
try
SaveDialog:=TSaveDialog.Create(self);
SaveDialog.Filter:='*.xls';
SaveDialog.FileName:='ExcelFileName';
try
if SaveDialog.Execute then
begin
DatasetToExcel(ClientDataSet1,DBGrid1,SaveDialog.FileName);
Application.MessageBox(PChar('Excel表保存完毕!'),'操作提示',MB_OK+MB_ICONInformation);
end;
except
Application.MessageBox(PChar('保存失败!'),'错误提示',MB_OK+MB_IconError);
end;
finally
SaveDialog.Free;
end;
end;
var
SaveDialog:TSaveDialog;
begin
try
SaveDialog:=TSaveDialog.Create(self);
SaveDialog.Filter:='*.xls';
SaveDialog.FileName:='ExcelFileName';
try
if SaveDialog.Execute then
begin
DatasetToExcel(ClientDataSet1,DBGrid1,SaveDialog.FileName);
Application.MessageBox(PChar('Excel表保存完毕!'),'操作提示',MB_OK+MB_ICONInformation);
end;
except
Application.MessageBox(PChar('保存失败!'),'错误提示',MB_OK+MB_IconError);
end;
finally
SaveDialog.Free;
end;
end;