怎样将dbgrid中的数据导入到excel中(200)

  • 主题发起人 主题发起人 wjhyyh
  • 开始时间 开始时间
W

wjhyyh

Unregistered / Unconfirmed
GUEST, unregistred user!
来个简单点儿的~~最好能用现成的控件~~多谢
 
用EHLIB的dbGridEh,可以直接用SaveDBGridEhToExportFile(TDBGridEhExportAsXLS, dbGridEh1, dlgSaveToExcel.FileName, True)将数据导出到EXCEL
 
将对应DataSet中的数据,按顺序从第一条记录到最后一条记录分别写入文件,字段之间采用chr(9)分割就可以。
 
写一个过程//转为EXCEL文件,支持多页面procedure TForm1.CopyDbDataToExcel(Args: array of const);var iCount, jCount: Integer; XLApp: Variant; Sheet: Variant; I: Integer;begin Screen.Cursor := crHourGlass; if not VarIsEmpty(XLApp) then begin XLApp.DisplayAlerts := False; XLApp.Quit; VarClear(XLApp); end; try XLApp := CreateOleObject('Excel.Application'); except Screen.Cursor := crDefault; Exit; end; XLApp.WorkBooks.Add; XLApp.SheetsInNewWorkbook := High(Args) + 1; for I := Low(Args) to High(Args) do begin XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args.VObject).Name; Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args.VObject).Name]; if not TDBGrid(Args.VObject).DataSource.DataSet.Active then begin Screen.Cursor := crDefault; Exit; end; TDBGrid(Args.VObject).DataSource.DataSet.first; for iCount := 0 to TDBGrid(Args.VObject).Columns.Count - 1 do Sheet.Cells[1, iCount + 1] := TDBGrid(Args.VObject).Columns.Items[iCount].Title.Caption; jCount := 1; while not TDBGrid(Args.VObject).DataSource.DataSet.Eof do begin for iCount := 0 to TDBGrid(Args.VObject).Columns.Count - 1 do Sheet.Cells[jCount + 1, iCount + 1] := TDBGrid(Args.VObject).Columns.Items[iCount].Field.AsString; Inc(jCount); TDBGrid(Args.VObject).DataSource.DataSet.Next; end; XlApp.Visible := True; end; Screen.Cursor := crDefault;end;引用这个过程就可以了。procedure TForm1.Excel1Click(Sender: TObject);beginCopyDbDataToExcel([DBGrid1]);end;
 
没考虑可能某些字段设置了OnGetText事件,Asstring-->DisplayText另外,对于全是数字的身份证号码,通过这种方式导出后,变成了数字类型,后面几位被丢失,Sheet.Cells[jCount + 1, iCount + 1] := ''''+TDBGrid(Args.VObject).Columns.Items[iCount].Field.DisplayText;速度不够快。可以直接写文件,字段之间用chr(9)分割。
 
procedure TForm1.Button1Click(Sender: TObject);var F:TextFile; DataSet:TDataSet; I:Integer;begin if not SaveDialog1.Execute then exit; if DBGrid1.DataSource.DataSet.State<>dsBrowse then Exit; AssignFile(F, SaveDialog1.FileName); Rewrite(F); For I:=0 To DBGrid1.Columns.Count-1 do if DBGrid1.Columns.Field<>nil then Write(F, DBGrid1.Columns.Title.Caption+chr(9)); DBGrid1.DataSource.DataSet.First; While not DBGrid1.DataSource.DataSet.Eof do begin WriteLn(F); For I:=0 To DBGrid1.Columns.Count-1 do if DBGrid1.Columns.Field<>nil then begin if DBGrid1.Columns.Field.DataType in [ftString,ftFixedChar, ftWideString] then Write(F, ''''+DBGrid1.Columns.Field.DisplayText+Chr(9) ) else write(F, DBGrid1.Columns.Field.DisplayText+Chr(9) ); end; DBGrid1.DataSource.DataSet.Next; end; CloseFile(F);end;这种写法比操作excell,速度要快10倍以上。
 
多人接受答案了。
 
后退
顶部