Procedure TurnToExcel(TmpDBGrid:TDBGrid);
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;