delphi - 将delphi stringgrid导出到excel

标签 delphi export-to-excel stringgrid

我正在尝试将数据从delphi 7 中的stringgrid 导出到microsoft excel。我一直在使用这段代码来做到这一点:

  objExcel := TExcelApplication.Create(nil);
  objExcel.Visible[LOCALE_USER_DEFAULT] := true;
  objWB := objExcel.workbooks.add(null,LOCALE_USER_DEFAULT);
  lineNumber := 1;

  for i:=1 to stringgrid1.rowcount-1 do begin
    for j:=0 to stringgrid1.ColCount-1 do begin
      objWB.Worksheets.Application.Cells.Item[i+lineNumber,j+1] := ''''+stringgrid1.Cells[j,i];
    end;
  end;

但是当数据量很大时,需要很长时间才能完成。还有其他更快的方法将数据从delphi 7 stringgrid导出到excel吗?

最佳答案

最快的方法是使用 Variant 数组,然后将整个数组传递给 Excel:

uses OleAuto;

var
  xls, wb, Range: OLEVariant;
  arrData: Variant;
  RowCount, ColCount, i, j: Integer;
begin
  {create variant array where we'll copy our data}
  RowCount := StringGrid1.RowCount;
  ColCount := StringGrid1.ColCount;
  arrData := VarArrayCreate([1, RowCount, 1, ColCount], varVariant);

  {fill array}
  for i := 1 to RowCount do
    for j := 1 to ColCount do
      arrData[i, j] := StringGrid1.Cells[j-1, i-1];

  {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;

关于delphi - 将delphi stringgrid导出到excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641897/

相关文章:

c++ - 如何使用 WM_* 消息调整窗口大小

c# - 导出当前gridview数据

delphi - 如何更改 Delphi Firemonkey XE7 中 Stringgrid 标题的字体大小?

delphi - Lazarus TStringGrid - 为单元格着色

delphi - 如何使网格在水平滚动时刷新

delphi - SignerSign() 失败。 (-2146869243/0x80096005)

mysql - 使用 Ruby 将 mysql 结果导出到文件

asp.net - 使用 IE 通过 https(SSL) 导出到 excel 在 asp.net 网站中不起作用

delphi - 未声明的 'FormCreate' 错误 Delphi

android - 在 firemonkey 中播放声音