The result is that it is slow to export data from dbgrideh to excel when creatoleobject is used (remember to use comobj );
Exporting a few records does not show much. If there are more than data records, it will take more than 10 minutes! Khan. The optimization effect is not obvious several times! The Code is as follows: function tform_bc.export_xls (xls_name: string): string;
VaR
Xls, sheet1: variant;
I, J: integer;
Begin
J: = 2;
Savedialog1.filename: = xls_name + '_' + formatdatetime ('yyyy-MM-DD ', now );
Savedialog1.filter: = 'excel file (*. xls) | *. xls ';
If not savedialog1.execute then exit;
Try
XLS: = createoleobject ('excel. application ');
Sheet1: = createoleobject ('excel. Sheet ');
Except
Showmessage ('excel startup failed, probably because Excel is not installed on your machine ');
Exit;
End;
XLS. Visible: = false;
Sheet1: = XLS. workbooks. Add;
Try
For I: = 0 to dbgrideh1.columns. Count-1 do
Sheet1.worksheets [1]. cells [1, I + 1]. Value: = dbgrideh1.columns [I]. Title. Caption;
With datamodule1.query _ ml do
Begin
First;
While not EOF do
Begin
For I: = 0 to fieldcount-1 do
Begin
Sheet1.worksheets [1]. cells [J, I + 1]. Value: = Fields [I]. asstring;
End;
INC (j );
Next;
End;
End;
Except
Showmessage ('data export failed! ');
End;
Try
Sheet1.saveas (savedialog1.filename );
Sheet1.close;
XLS. Quit;
Except
Sheet1.close;
XLS. Quit;
End;
XLS: = unassigned; sheet1: = unassigned;
The advantage of this method is that you can operate on each cell in Excel, but it is too slow when the data volume is large. The possible reason for analysis for a long time is that this method requires starting Excel and performing operations on each cell!