问题是您正在为每个单元格调用 Excel 对象;在最好的情况下,这是一个缓慢的操作,因此对大量单元执行此操作将需要很长时间。不久前我有一个案例:4000 行 9 列需要大约 44 秒才能传输到 Excel。
我目前的解决方案包括创建一个 csv 文件,然后将该 csv 导入 Excel。
const
fn = 'c:\windows\temp\csv.csv';
var
csv: tstringlist;
row, col: integer;
s: string;
begin
csv:= tstringlist.create;
for row:= 1 to stringgrid1.rowcount do
begin
s:= '';
for col:= 0 to stringgrid1.ColCount-1 do
s:= s + stringgrid1.Cells[col, row-1] + ',';
csv.add (s)
end;
csv.savetofile (fn);
csv.free;
objExcel := TExcelApplication.Create(nil);
objExcel.workbooks.open (fn);
deletefile (fn);
end;
另一种方法来自Mike Shkolnik,我按原样引用:
var
xls, wb, Range: OLEVariant;
arrData: Variant;
begin
{create variant array where we'll copy our data}
arrData := VarArrayCreate([1, yourStringGrid.RowCount, 1, yourStringGrid.ColCount], varVariant);
{fill array}
for i := 1 to yourStringGrid.RowCount do
for j := 1 to yourStringGrid.ColCount do
arrData[i, j] := yourStringGrid.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[yourStringGrid.RowCount, yourStringGrid.ColCount]];
{copy data from allocated variant array}
Range.Value := arrData;
{show Excel with our data}
xls.Visible := True;
end;
我建议您尝试这两种方法,看看哪种方法更适合您的目的。