Delphi 控制Excel(4)

数据导出为Excel格式
首先要创建一个公共单元,名字你们可以随便起。
以下是我创建的公共单元的全部代码:
unit UnitDatatoExcel;
interface
uses
  Windows,Messages, SysUtils, Classes, Graphics,Controls, Forms,Dialogs,
  DB, ComObj;
type
  TKHTMLFormatCellEvent = procedure(Sender:TObject; CellRow,CellColumn: Integer; FieldName: string;
    varCustomAttrs, CellData: string) of object;
  TDataSetToExcel = class(TComponent)
  private
    FDataSet:TDataSet;
   FOnFormatCell: TKHTMLFormatCellEvent;
  public
    constructorCreate(AOwner: TComponent); override;
    destructorDestroy; override;
    procedureTransfer(const FileName: string; Title: string = ');
  published
    propertyDataSet: TDataSet read FDataSet write FDataSet;
  end;
implementation
constructor TDataSetToExcel.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FDataSet := nil;
end;
destructor TDataSetToExcel.Destroy;
begin
  inherited;
end;
procedure TDataSetToExcel.Transfer(constFileName:string;Title:string = ');
var
  ExcelApp, MyWorkBook: Variant;
  i: byte;
  j, a: integer;
  s, k, b, CustomAttrs: string;
begin
  try
    ExcelApp :=CreateOleObject('Excel.Application');
    MyWorkBook:= CreateOleObject('Excel.Sheet');
  except
    on Exceptiondo raise exception.Create('无法打开Excel文件,请确认已经安装Execl')
  end;
  MyWorkBook := ExcelApp.WorkBooks.Add;
 MyWorkBook.WorkSheets[1].Range['A1:D1'].Merge(True);
 MyWorkBook.WorkSheets[1].Range['A1:D2'].HorizontalAlignment :=$FFFFEFF4;
  MyWorkBook.WorkSheets[1].Cells[1, 1].Value :=Title;
  with FDataSet do
  begin
    i :=2;
    for j := 0to FieldCount - 1 do
    begin
     if Fields[j].Visible then
     begin
       b := Fields[j].DisplayLabel;
       CustomAttrs := ';
       if Assigned(FOnFormatCell) then
         FOnFormatCell(Self, 1, i,
           Fields[j].FieldName, CustomAttrs, b);
       MyWorkBook.WorkSheets[1].Cells[i, j + 1].Value := b;
     end;
    end;
    i :=3;
    Close;
    Open;
    First;
    a :=2;
    while notEof do
    begin
     for j := 0 to FieldCount - 1 do
     begin
       if Fields[j].Visible then
       begin
         CustomAttrs := ';
         k := Fields[j].Text;
         if Assigned(FOnFormatCell) then
           FOnFormatCell(Self, i, a,
             Fields[j].FieldName, CustomAttrs, k);
         MyWorkBook.WorkSheets[1].Cells[i, j + 1].Value := k;
         inc(a);
       end;
    

你可能感兴趣的:(Delphi 控制Excel(4))