Procedure TfrmMDIbase.DatatoExcel(printflag: boolean);
Var
year, month, day: Word;
row, column, record_count, temcount: integer;
vExcel, vbook: variant; //定義excel,sheet變量
Begin
If pub_dataset.RecordCount < 1 Then
Begin
MessageBox(0, '目前沒有導出的記錄資料,系統將不執行導出!', '提示', Mb_ok + mb_Iconstop);
Exit;
End;
Try
vExcel := createoleobject('Excel.application');
vbook := createoleobject('Excel.sheet');
Except
MessageBox(0, '無法啟動Excel程序,請確認是否安裝了Excel!', '警告', Mb_ok + mb_Iconstop);
Exit;
End;
DecodeDate(Now, year, month, day); //分解日期
fieldscount := pub_Grid.Columns.Count;
record_count := pub_dataset.RecordCount; //記錄數目
Try
vbook := vExcel.workbooks.Add[Excel_file]; //打開現有模板
vExcel.cells(2, 1) := '制表者:' + UserLoginName;
temcount := 0;
For row := 1 To fieldscount Do
If pub_Grid.Columns[row - 1].Visible Then
inc(temcount);
vExcel.cells(2, temcount - 1) := '列印日期:' + IntToStr(year) + '-' + IntToStr(month) + '-' + IntToStr(day);
pub_dataset.First;
column := 3;
temcount := 1;
ProgressBar1.Visible := True;
ProgressBar1.Position := 0; {進度初始化}
ProgressBar1.Min := 0;
ProgressBar1.Max := record_count;
pub_datasource.DataSet.DisableControls; //斷開於數據集連接
While Not (pub_dataset.Eof) Do
Begin
column := column + 1;
For row := 1 To fieldscount Do
Begin
If pub_Grid.Columns[row - 1].Visible Then Begin
vExcel.cells(column, temcount) := pub_Grid.Fields[row - 1].Value;
inc(temcount);
End;
End;
temcount := 1;
pub_dataset.Next;
ProgressBar1.StepBy(1);
End;
pub_dataset.First;
pub_datasource.DataSet.EnableControls;
ProgressBar1.Visible := False;
If printflag Then //判斷是否打印模式
Begin
If Msbox('當前報表已經生成,請問是否開啟Excel應用程序.', Sysquestion, MB_ICONQUESTION + MB_Yesno) = Idyes Then
Begin
vExcel.Visible := True;
End
Else
Begin
SaveDialog1.DefaultExt := 'xls';
SaveDialog1.Filter := '*.xls|*.xls';
SaveDialog1.filename := filename;
If SaveDialog1.Execute Then
vbook.saveas(SaveDialog1.filename);
vExcel.Visible := False;
vbook.close; //釋放資源
vExcel.quit;
vExcel := unassigned;
End;
End
Else
Begin
vbook.saveas(filename);
Msbox('當前數據已導出為:' + #10 + #13 + Excel_file + '文件成功.', Sysquestion, MB_ICONQUESTION + Mb_ok);
vbook.close;
vExcel.quit;
vExcel := unassigned;
End;
Except
Raise;
End;
End;
對上面修改一下,你就可以用了。