簡體   English   中英

在Delphi中從SQLite導出到Excel

[英]Exporting from SQLite to Excel in Delphi

我使用TSQLConnection通過以下過程從SqlLite導出數據:

  Campos := TStringList.Create;
  SQLiteConnection.Execute('SELECT * FROM tabela', nil, results);
  if not results.IsEmpty then
  begin
    results.GetFieldNames(Campos);

    XLApp1 := createoleobject('excel.application');
    XLApp1.Workbooks.Add(xlWBatWorkSheet);
    Sheet := XLApp1.Workbooks[1].WorkSheets[1];
    linha := 1;
    begin
       pBar.Max := results.RecordCount;
       for coluna := 0 to results.FieldCount - 1 do
           Sheet.Cells[1, coluna + 1]  :=  Campos[coluna];

       while ( not results.Eof ) do
       begin
          linha := linha + 1;
          for coluna := 0 to results.FieldCount - 1 do
              Sheet.Cells[linha, coluna + 1]  :=  results.FieldByName(campos[coluna]).AsString;
          results.next;
          pBar.Position := pBar.Position + 1;
          Application.ProcessMessages;
       end;
   end;

);

它工作正常。 但這需要太多時間才能完成。 使用SSD導出帶有40,000條記錄和45個字段的i7筆記表的35分鍾。

所以我的問題是:我有可能做得更快一點嗎?

最簡單的方法是將所有數據收集到一個變量數組中,然后一次性傳遞給Excel。 很大一部分時間是寫入Excel,將其減少到一次寫入操作要快得多。

下面的代碼改編自代碼,以將數據從TStringGrid傳輸到Excel工作表。 Results來自您的原始代碼,因此請考慮它的設置與您在上面所指示的完全相同。 (以下代碼未經測試修改,因為很明顯我沒有你的數據要測試。它與stringgrid一起工作,正如我所提到的 - 我無法測試適應性。如果你遇到問題,請離開評論,我會嘗試解決它們。)

使用40個行的35個字段,您可能需要將其分解為塊(即使一次執行幾百行也是一次性執行一次的主要性能改進)。

var
  xls, wb, Range: OLEVariant;
  arrData: Variant;
  RowCount, ColCount, i, j: Integer;
begin
  // Set up your dataset as Result here, just as in your own code
  // ....

  //create variant array where we'll copy our data
  RowCount := Results.RecordCount;
  ColCount := StringGrid1.FieldCount;
  arrData := VarArrayCreate([1, RowCount, 1, ColCount], varVariant);

  //fill array
  j := 1;
  while not Results.Eof do
  begin
    for i := 1 to ColCount do
      arrData[i, j] := Results.Fields[i].AsString;
    Inc(j);
    Results.Next;
  end;

  //initialize an instance of Excel
  xls := CreateOLEObject('Excel.Application');

  //create workbook
  wb := xls.Workbooks.Add;

  //retrieve a range where data must be placed
  Range := wb.WorkSheets[1].Range[wb.WorkSheets[1].Cells[1, 1],
                                  wb.WorkSheets[1].Cells[RowCount, ColCount]];

  //copy data from allocated variant array
  Range.Value := arrData;

  //show Excel with our data
  xls.Visible := True;
end;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM