ADOQuery导出Excel超快(大量数据)!

function TWorkWindowForm.ADOQuery2Excel(AcxGridDBTableView:TcxGridDBTableView; ADOQuery:TADOQuery; var sMsg:string): Boolean;
var
  xlApp, xlBook, xlSheet, xlQuery: Variant;
  SQLCmd, lv_sPath: string;
  i, n, m: Integer;
  x, y: Cardinal;
  SaveDialog: TSaveDialog;
begin
  Result := False;
  if ADOQuery.IsEmpty then Exit;

  //获取保存路径
  SaveDialog := TSaveDialog.Create(nil);
  try
    with SaveDialog do
    begin
      Filter := '*.xlsx|*.xlsx';
      if Execute then
        lv_sPath := SaveDialog.FileName;
      if Trim(lv_sPath) = '' then
      begin
        sMsg := '不允许保存Excel路径为空!';
        Exit;
      end;
      if ExtractFileExt(lv_sPath) <> '.xlsx' then
      begin
        lv_sPath := lv_sPath + '.xlsx';
      end;
      if FileExists(lv_sPath) then
      begin
        if Application.MessageBox('存在相同文件,是否删除?', '提示', MB_ICONQUESTION + MB_YESNO) = IDYES then
        begin
          DeleteFile(lv_sPath);
        end else
        begin
          sMsg := '未删除相同文件!';
          Exit;
        end;
      end;
    end;
  finally
    SaveDialog.Free;
  end;

  x := GetTickCount;
  try
    //建立OLE对象
    xlApp := CreateOleObject('Excel.Application');
    xlBook := xlApp.Workbooks.Add;
    xlSheet := xlBook.Worksheets['sheet1'];
    xlApp.Visible := false;
  except
    on e:Exception do
    begin
      sMsg := '创建Excel失败,请确认安装Excel2007或以上版本!' + #13#10 + e.Message;
      Exit;
    end;
  end;

  //设置excel默认格式
  xlSheet.Cells.Font.Name := '宋体';
  xlSheet.Cells.Font.Size := 10;
  xlSheet.Cells.VerticalAlignment := 2;

  //写入表头
  m := AcxGridDBTableView.ItemCount;  //cxGrid列总数
//  xlSheet.Range['A1'].Value := '列标S1';
  for i:=0 to m-1 do
  begin
    xlApp.cells[1,i+1]:=AcxGridDBTableView.Columns[i].Caption;   //左上角第一个方格是[1,1]
  end;

  try
    try
      xlQuery := xlSheet.QueryTables.Add(ADOQuery.Recordset, xlSheet.Range['A2']);
      xlQuery.Refresh;
      xlSheet.Rows[2].Delete;   //删除第2行的字段标题[xlApp.ActiveSheet.Rows[2].Delete]
      xlBook.SaveAs(lv_sPath);
    except
      on e:Exception do
      begin
        sMsg := '导出数据异常Exception!' + #13#10 + e.Message;
        Exit;
      end;
    end;
    y := GetTickCount;
    sMsg := '共计' + IntToStr(ADOQuery.RecordCount) + '条记录,耗费:' + FloatToStr((y - x) / 1000) + '秒!';
    FFactoryIntf.getLogIntf.LogInfo(sMsg);
    Result := True;
  finally
    if not VarIsNull(xlApp) then    //释放OLE对象
    begin
      xlBook.Close; //关闭工作簿
      xlApp.Quit;   //退出Excel进程
      xlApp := Unassigned;
      xlApp := NULL;
    end;
  end;
end;

 

posted @ 2018-10-10 17:43  襄阳古城  阅读(1007)  评论(0编辑  收藏  举报