如题所述,答对即给分
通过DBGridEh直接导出到Excel
Procedure TurnToExcel(TmpDBGrid:TDBGridEh);
var
MyExcel: Variant;
WorkBook: OleVariant;
WorkSheet: OleVariant;
i,j:integer;
xlsfilename :string;
Savedialog1 :TSaveDialog;
begin
if Application.MessageBox(确认导出到Excel?,App_caption,MB_ICONQUESTION+MB_YESNO)=mrno then
Abort;
SaveDialog1 :=TSaveDialog.create(Application);
SaveDialog1.Filter := Excel文件(*.xls)|*.XLS;
if savedialog1.Execute then
if savedialog1.FileName <> then
begin
xlsfilename :=savedialog1.FileName;
try
MyExcel:=CreateOleObject(Excel.Application);
MyExcel.Application.WorkBooks.Add;
MyExcel.Caption:=将数据导入到EXCEL表中;
MyExcel.Application.Visible:=false;
WorkBook:=MyExcel.Application.workbooks[1];
worksheet:=workbook.worksheets.item[1];
except
Application.MessageBox(EXCEL不存在!,App_caption,MB_ICONERROR+MB_OK);
Savedialog1.Free;
workBook.Saved := True;
WorkBook.close;
MyExcel.Quit;//释放VARIANT变量
MyExcel:=Unassigned;
end;
i:=1;
Frm_system_progress :=TFrm_system_progress.create(Application);
Try
with TmpDBGrid.DataSource.DataSet do
begin
Open;
DisableControls;
with Frm_system_progress.ProgressBar_temp do
begin
min :=0;
max :=TmpDBGrid.Columns.Count*recordcount;
Position :=0;
end;
Frm_system_progress.label_progress.caption :=正在导出到Excel...;
Frm_system_progress.Show;
Frm_system_progress.update;
for j:=0 to TmpDBGrid.Columns.Count-1 do
begin
if TmpDBGrid.Columns[j].Visible=true then
worksheet.cells[1,j+1]:=TmpDBGrid.Columns[j].Title.Caption;
end;
First;
while not Eof do
begin
inc(i);
for j:=0 to TmpDBGrid.Columns.Count-1 do
begin
if TmpDBGrid.Columns[j].Visible=true then
begin
worksheet.cells[i,j+1].NumberFormatLocal :=@;
worksheet.cells[i,j+1]:=TmpDBGrid.Columns[j].Field.AsString ;
Frm_system_progress.ProgressBar_temp.StepIt;
end;
end;
next;
end;
EnableControls;
end;
WorkBook.saveas(XlsFileName);
Frm_system_progress.ProgressBar_temp.position :=TmpDBGrid.Columns.Count*TmpDBGrid.DataSource.DataSet.RecordCount;
Application.MessageBox(导出到Excel成功!,App_caption,MB_ICONINFORMATION+MB_OK);
Frm_system_progress.Free;
MyExcel.Quit;
MyExcel := Unassigned;
Savedialog1.Free;
except
Application.MessageBox(导出到Excel失败!,App_caption,MB_ICONWARNING+MB_OK);
workBook.Saved := True;
WorkBook.close;
MyExcel.Quit;//释放VARIANT变量
MyExcel:=Unassigned;
Frm_system_progress.Free;
Savedialog1.Free;
end;
end;
end;
方法1:通过ole调用,就如楼上的方法一样,缺点是遇到大量数据时要死机、速度慢。
方法2:通过EHLIB提供的接口调用,速度奇快。
在uses子句中添加 DBGridEhImpExp 单元,
procdure form1.Exporttoxls;
var filename:string;
ff:TDBGridEhExportAsXLS; //声明一个导出到XLS的类。
begin
if savedialog1.Execute then begin
filename:=sdlg.FileName ;
if filename= then exit;
try
ff:=TDBGridEhExportAsXLS.create; //建立类的实例
ff.DBGridEh :=dbgrid1;
filename:=filename+.xls;
ff.ExportToFile(filename,true); //导出到XLS文件
finally
ff.Free ; //释放所占用的Mem.
end;
end;
end;