现在的位置: 首页 > 综合 > 正文

在DELPHI中实现数据导出到Excel

2013年06月28日 ⁄ 综合 ⁄ 共 640字 ⁄ 字号 评论关闭
在uses子句中加入ComObj。
procedure TfmExcel.btnOutToExcelClick(Sender: TObject);
var
  VarExcel: Variant;
  Col,Row:Integer;
begin
  if SaveDialog1.Execute then
  begin
    VarExcel:=CreateOleObject('Excel.Application');
    VarExcel.Workbooks.Add;

    with ADOQuery1 do
    begin
      Open;
      //导出字段名称
      for Col:=0 to (Fields.Count-1) do
        VarExcel.Cells[1,Col+1]:=Fields[Col].FieldName;
      //导出数据
      for Row:=0 to (RecordCount-1) do
        for Col:=0 to (Fields.Count-1) do
          VarExcel.Cells[Row+2,Col+1]:=Fields[Col].AsString;
      Close;
    end;

    VarExcel.ActiveSheet.SaveAs(SaveDialog1.FileName); //保存Excel文件
    VarExcel.ActiveWorkBook.Close;
    VarExcel.Quit;
  end;
end;  

抱歉!评论已关闭.