|
|
以下在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; |
|