的问题是,您所要求的每一个细胞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;
我建议您尝试两种方法,看看哪是你的目的更快。
感谢您的快速反应,伙计们。我认为数组方法最适合我的情况,因为我不打算使用.csv文件。我如何将这个问题标记为“已解决”? – dapidmini