还有其它 好多方法,有针对DataSet的,有针对DBGRid的,这个是我最常用的。procedure TfrmFunc.DBGridToExcel(const ADBGrid:TDBGrid); var i,j:integer; ExcelApp:Variant; WorkBook:oleVariant; WorkSheet:oleVariant; BM:TBookMark; begin BM:=nil; if MessageBox(Handle,'确定导出吗?','询问',mb_yesno+mb_iconQuestion)=idyes then begin if not ADBGrid.DataSource.DataSet.Active then begin MessageBox(Handle,'数据集没有打开,无法导出',MB_OK+MB_IconWarning); exit; end; Screen.Cursor:=crHourGlass; try ExcelApp:=CreateOleObject('Excel.Application'); ExcelApp.Application.workBooks.add; workbook:=ExcelApp.application.workbooks[1]; worksheet:=workbook.worksheets.item[1]; except MessageBox(Handle,'请确定Excel已经正确安装',MB_OK+MB_ICONWARNing); Screen.Cursor:=crDefault; Exit; end; i:=1; try for j:=0 to ADBGrid.DataSource.DataSet.FieldCount-1 do begin WorkSheet.cells[i,j+1]:=ADBGrid.DataSource.DataSet.Fields[j].DisplayLabel; WorkSheet.cells[i,j+1].font.size:=12; WorkSheet.cells[i,j+1].font.bold:=true; end; BM:=ADBGrid.DataSource.DataSet.GetBook; ExcelApp.Application.visible:=True; AdBGrid.DataSource.DataSet.first; while not AdBGrid.DataSource.DataSet.eof do begin inc(i); for j:=0 to AdBGrid.DataSource.DataSet.fieldcount-1 do begin WorkSheet.cells[i,j+1].NumberFormat:='@'; worksheet.cells[i,j+1]:=AdBGrid.DataSource.DataSet.fields[j].asstring; end; AdBGrid.DataSource.DataSet.next; end; MessageBox(Handle,'成功导出','恭喜',64); finally ADBGrid.DataSource.DataSet.GotoBook(BM); ADBGrid.DataSource.DataSet.FreeBook(BM); Screen.Cursor:=crDefault; end; end; end;
var
i,j:integer;
ExcelApp:Variant;
WorkBook:oleVariant;
WorkSheet:oleVariant;
BM:TBookMark;
begin
BM:=nil;
if MessageBox(Handle,'确定导出吗?','询问',mb_yesno+mb_iconQuestion)=idyes then
begin if not ADBGrid.DataSource.DataSet.Active then
begin
MessageBox(Handle,'数据集没有打开,无法导出',MB_OK+MB_IconWarning);
exit;
end; Screen.Cursor:=crHourGlass;
try
ExcelApp:=CreateOleObject('Excel.Application');
ExcelApp.Application.workBooks.add;
workbook:=ExcelApp.application.workbooks[1];
worksheet:=workbook.worksheets.item[1]; except
MessageBox(Handle,'请确定Excel已经正确安装',MB_OK+MB_ICONWARNing);
Screen.Cursor:=crDefault;
Exit;
end;
i:=1; try
for j:=0 to ADBGrid.DataSource.DataSet.FieldCount-1 do
begin
WorkSheet.cells[i,j+1]:=ADBGrid.DataSource.DataSet.Fields[j].DisplayLabel;
WorkSheet.cells[i,j+1].font.size:=12;
WorkSheet.cells[i,j+1].font.bold:=true;
end; BM:=ADBGrid.DataSource.DataSet.GetBook; ExcelApp.Application.visible:=True; AdBGrid.DataSource.DataSet.first;
while not AdBGrid.DataSource.DataSet.eof do
begin
inc(i);
for j:=0 to AdBGrid.DataSource.DataSet.fieldcount-1 do
begin
WorkSheet.cells[i,j+1].NumberFormat:='@'; worksheet.cells[i,j+1]:=AdBGrid.DataSource.DataSet.fields[j].asstring;
end; AdBGrid.DataSource.DataSet.next;
end;
MessageBox(Handle,'成功导出','恭喜',64);
finally
ADBGrid.DataSource.DataSet.GotoBook(BM);
ADBGrid.DataSource.DataSet.FreeBook(BM); Screen.Cursor:=crDefault;
end;
end;
end;
问题解决了!!!