导出delphi stringgrid到excel [英] export delphi stringgrid to excel

查看:685
本文介绍了导出delphi stringgrid到excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to export data from a stringgrid in delphi 7 to microsoft excel. I have been using this code to do it:

  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?

but when the data is big, it takes a very long time to finish. is there other faster way to export data from delphi 7 stringgrid to excel?

推荐答案

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

The quickest way is to use an array of Variant,and just pass the entire array to Excel:

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 stringgrid到excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆