gpt4 book ai didi

delphi - 将delphi stringgrid导出到excel

转载 作者:行者123 更新时间:2023-12-03 14:49:17 25 4
gpt4 key购买 nike

我正在尝试将数据从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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com