找回密码
 立即注册
查看: 1344|回复: 0

Delphi总如何导出EXcel

[复制链接]

6782

主题

8

回帖

2万

积分

管理员

积分
21777
发表于 2019-5-20 21:42:25 | 显示全部楼层 |阅读模式
以下在Delphi6下通过,注意:本过程未检测Execl是否安装正确!

procedure TForm1.DBGridToExcel(dgrSource: TDBGrid);
var            //从DBGrid导出到Excel
MyExcel, varCells: Variant;
MyCells, Cell1, Cell2, Range: OleVariant;
iRow, iCol: integer;
CurPos: TBookmark;
begin
dgrSource.DataSource.DataSet.DisableControls;
MyExcel := CreateOleObject('Excel.Application');
MyExcel.WorkBooks.Add;
MyExcel.Visible := False;
MyCells := MyExcel.WorkBooks[1].WorkSheets[1].Cells;
CurPos  := dgrSource.DataSource.DataSet.GetBookmark;
dgrSource.DataSource.DataSet.First;

iRow := 1;
for iCol := 1 to dgrSource.FieldCount do
begin
   MyExcel.WorkBooks[1].WorkSheets[1].Cells[iRow,iCol] :=
                                   dgrSource.Fields[iCol-1].DisplayName;
   MyExcel.WorkBooks[1].WorkSheets[1].Cells[iRow,iCol].Select;
   MyExcel.Selection.Font.Bold := true;
   MyExcel.WorkBooks[1].WorkSheets[1].Columns[iCol].ColumnWidth :=
                                   dgrSource.Fields[iCol-1].DisplayWidth;
end;
Inc(iRow);
varCells := VarArrayCreate([1,
                             dgrSource.DataSource.DataSet.RecordCount,
                             1,
                             dgrSource.FieldCount], varVariant);
//VarArrayLock(varCells);
while not dgrSource.DataSource.DataSet.Eof do
begin
   for iCol := 1 to dgrSource.FieldCount do
   begin
     varCells[iRow-1, iCol] := dgrSource.Fields[iCol-1].AsString;
   end;
   Inc(iRow);
   dgrSource.DataSource.DataSet.Next;
end;
//ExcelWorksheet1.Cells.Item
//VarArrayUnLock(varCells);
Cell1 := MyCells.Item[2, 1];
Cell2 := MyCells.Item[dgrSource.DataSource.DataSet.RecordCount + 1,
                       dgrSource.FieldCount];
Range := MyExcel.WorkBooks[1].WorkSheets[1].Range[Cell1 ,Cell2];
Range.Value := varCells;
MyCells  := Unassigned;
Cell1    := Unassigned;
Cell2    := Unassigned;
Range    := Unassigned;
varCells := Unassigned;  //此句挺花时间,如果注释掉,则 -> **1  2003.12.05
MyExcel.WorkBooks[1].WorkSheets[1].Cells[1,1].Select;
MyExcel.Visible := True;
MyExcel  := Unassigned;  //**1: 此句又要用许多时间,如果注释掉,则 -> **2
if CurPos <> nil then
begin
   dgrSource.DataSource.DataSet.GotoBookmark(CurPos);
   dgrSource.DataSource.DataSet.FreeBookmark(CurPos);
end;
dgrSource.DataSource.DataSet.EnableControls; //**2:此句又要花很多时间!
end;
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表