我想把我查询的结果导到excel中去。没有思路。希望大家给出例子。谢谢!(100分)

  • 主题发起人 主题发起人 香水雨落
  • 开始时间 开始时间

香水雨落

Unregistered / Unconfirmed
GUEST, unregistred user!
姓名 数学 语文 英语
张三 80 85 90
李四 75 70 88
王二 90 80 75
谢谢各位,一定给分!
 
来自:yzhshi, 时间:2001-12-2 10:04:00, ID:758347
代码:
既然大家都在这里将自己的东西贴出来,那我就再贴一个,将DBGrid中的文件转换到Excel中或者转换到Txt中的控件。
我自己编写的,希望大家讨论一下。
unit DBGridExport;

interface

uses
  SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, Db, DBGrids, Comobj, extctrls, comctrls, ActiveX;

type
  TSpaceMark = (csComma, csSemicolon, csTab, csBlank, csEnter);

  TDBGridExport = class(TComponent)
  private
    FDB_Grid: TDBGrid;                                      {读取DBGrid的源}

    FTxtFileName: string;                                   {文本文件名}
    FSpaceMark: TSpaceMark;                                 {间隔符号}
    FSpace_Ord: Integer;                                    {间隔符号的Asc数值}
    FTitle: string;                                         {显示的标题}
    FSheetName: string;                                     {工作表标题}
    FExcel_Handle: OleVariant;                              {Excel的句柄}

    FWorkbook_Handle: OleVariant;                           {书签的句柄}

    FShow_Progress: Boolean;                                {是否显示插入进度}

    FProgress_Form: TForm;                                  {进度窗体}
    FRun_Excel_Form: TForm;                                 {启动Excel提示窗口}
    FProgressBar: TProgressBar;                             {进度条}

    function Connect_Excel: Boolean;                        {启动Excel}
    function New_Workbook: Boolean;                         {插入新的工作博}
    function InsertData_To_Excel: Boolean;                  {插入数据}
    procedure Create_ProgressForm(AOwner: TComponent);      {创建进度显示窗口}
    procedure Create_Run_Excel_Form(AOwner: TComponent);    {创建启动Excel窗口}
    procedure SetSpaceMark(Value: TSpaceMark);              {设置导出时的间隔符号}
  protected
  public
    constructor Create(AOwner: TComponent); override;       {新建}
    destructor Destroy; override;                           {销毁}
    function Export_To_Excel: Boolean; overload;            {导出到Excel中}
    function Export_To_Excel(DB_Grid: TDBGrid): Boolean; overload;

    function Export_To_Txt(NewFile: Boolean = True): Boolean; overload; {导出到文本文件中}
    function Export_To_Txt(FileName: string; NewFile: Boolean = True): Boolean; overload;
    function Export_To_Txt(DB_Grid: TDBGrid; NewFile: Boolean = True): Boolean; overload;
    function Export_To_Txt(FileName: string; DB_Grid: TDBGrid; NewFile: Boolean = True): Boolean; overload;

  published
    property DB_Grid: TDBGrid read FDB_Grid write FDB_Grid;
    property Show_Progress: Boolean read FShow_Progress write FShow_Progress;
    property TxtFileName: string read FTxtFileName write FTxtFileName;
    property SpaceMark: TSpaceMark read FSpaceMark write SetSpaceMark;
    property Title: string read FTitle write FTitle;
    property SheetName: string read FSheetName write FSheetName;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Stone', [TDBGridExport]);
end;

{-------------------------------------------------------------------------------}
{新建}
constructor TDBGridExport.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FShow_Progress := True;
  FSpaceMark := csTab;
end;

{销毁}
destructor TDBGridExport.Destroy;
begin
  varClear(FExcel_Handle);
  varClear(FWorkbook_Handle);
  inherited Destroy;
end;

{===============================================================================}
{导出到文本文件中}
function TDBGridExport.Export_To_Txt(NewFile: Boolean = True): Boolean;
var
  Txt: TStrings;
  Tmp_Str: string;
  data_Str: string;
  i, j: Integer;
  Column_name: string;
  Data_Set: TDataSet;

  bookmark: pointer;
  Before_Scroll, Afrer_Scroll: TDataSetNotifyEvent;
begin
  Result := False;

  if NewFile = True then
    FTxtFileName := '';
  if FTxtFileName = '' then
  begin
    with TSaveDialog.Create(nil) do
    begin
      Title := '请选择输出文件名';
      DefaultExt := 'txt';
      Filter := '文本文件(*.Txt)|*.txt';
      Options := [ofOverwritePrompt, ofHideReadOnly, ofPathMustExist, ofNoReadOnlyReturn, ofEnableSizing];
      if Execute then
        FTxtFileName := FileName;
      Free;
      if FTxtFileName = '' then                             {如果没有选中文件,则直接推出}
        exit;
    end;

    if FTxtFileName = '' then
    begin
      raise exception.Create('没有指定输出文件');
      Exit;
    end;

  end;

  if FDB_Grid = nil then
    raise exception.Create('请输入DBGrid名称');

  Txt := TStringList.Create;
  try
    {显示插入进度}
    if FShow_Progress = True then
    begin
      Create_ProgressForm(nil);
      FProgress_Form.Show;
    end;

    {第一行,插入标题}
    Tmp_Str := '';                                          //FDB_Grid.Columns[0].Title.Caption;
    for i := 1 to FDB_Grid.Columns.Count do
      if FDB_Grid.Columns[i - 1].Visible = True then
        Tmp_Str := Tmp_Str + FDB_Grid.Columns[i - 1].Title.Caption + Chr(FSpace_Ord);

    Tmp_Str := Copy(Tmp_Str, 1, Length(Tmp_Str) - 1);

    Txt.Add(Tmp_Str);

   {插入DBGrid中的数据}
    Data_Set := FDB_Grid.DataSource.DataSet;
   {记忆当前位置并取消任何事件}
//  new(bookmark);
    bookmark := Data_Set.GetBookmark;

    Data_Set.DisableControls;
    Before_Scroll := Data_Set.BeforeScroll;
    Afrer_Scroll := Data_Set.AfterScroll;
    Data_Set.BeforeScroll := nil;
    Data_Set.AfterScroll := nil;

    if FShow_Progress = True then
    begin
      Data_Set.Last;
      FProgress_Form.Refresh;
      FProgressBar.Max := Data_Set.RecordCount;
    end;

    {插入DBGrid中的所有字段}
    Data_Set.First;

    j := 2;
    while not Data_Set.Eof do
    begin
      if FShow_Progress = True then
        FProgressBar.Position := j - 2;

      Column_name := FDB_Grid.Columns[0].FieldName;
      Tmp_Str := '';                                        //Data_Set.FieldByName(Column_name).AsString;
      for i := 1 to FDB_Grid.Columns.Count do
        if FDB_Grid.Columns[i - 1].Visible = True then
        begin
          data_Str := FDB_Grid.Fields[i - 1].DisplayText;
          Tmp_Str := Tmp_Str + data_Str + Chr(FSpace_Ord);
        end;

      Tmp_Str := Copy(Tmp_Str, 1, Length(Tmp_Str) - 1);
      Txt.Add(Tmp_Str);

      j := j + 1;
      Data_Set.Next;
    end;

    {恢复原始事件以及标志位置}
    Data_Set.GotoBookmark(bookmark);
    Data_Set.FreeBookmark(bookmark);
//  dispose(bookmark);
    Data_Set.EnableControls;
    Data_Set.BeforeScroll := Before_Scroll;
    Data_Set.AfterScroll := Afrer_Scroll;

    {写到文件}
    Txt.SaveToFile(FTxtFileName);
    Result := True;
  finally
    Txt.Free;
    if FShow_Progress = True then
    begin
      FProgress_Form.Free;
      FProgress_Form := nil;
    end;
  end;
end;

function TDBGridExport.Export_To_Txt(FileName: string; NewFile: Boolean = True): Boolean;
begin
  FTxtFileName := FileName;
  Result := Export_To_Txt(NewFile);
end;

function TDBGridExport.Export_To_Txt(DB_Grid: TDBGrid; NewFile: Boolean = True): Boolean;
begin
  FDB_Grid := DB_Grid;
  Result := Export_To_Txt(NewFile);
end;

function TDBGridExport.Export_To_Txt(FileName: string; DB_Grid: TDBGrid; NewFile: Boolean = True): Boolean;
begin
  FTxtFileName := FileName;
  FDB_Grid := DB_Grid;
  Result := Export_To_Txt(NewFile);
end;

{-------------------------------------------------------------------------------}
{设置导出时的间隔符号}
procedure TDBGridExport.SetSpaceMark(Value: TSpaceMark);
begin
  FSpaceMark := Value;
  case Value of
    csComma: FSpace_Ord := ord(',');
    csSemicolon: FSpace_Ord := ord(';');
    csTab: FSpace_Ord := 9;
    csBlank: FSpace_Ord := 32;
    csEnter: FSpace_Ord := 13;
  end;
end;


{===============================================================================}
{导出到Excel中}
function TDBGridExport.Export_To_Excel: Boolean;
begin
  if FDB_Grid = nil then
    raise exception.Create('请输入DBGrid名称');

  Result := False;
  if Connect_Excel = True then
    if New_Workbook = True then
      if InsertData_To_Excel = True then
        Result := True;
end;

function TDBGridExport.Export_To_Excel(DB_Grid: TDBGrid): Boolean;
begin
  FDB_Grid := DB_Grid;
  Result := Export_To_Excel;
end;


{-------------------------------------------------------------------------------}
{启动Excel}
function TDBGridExport.Connect_Excel: Boolean;
  {连接Ole对象}
  function My_GetActiveOleObject(const ClassName: string; out Ole_Handle: IDispatch): Boolean;
  var                                                       //IDispatch
    ClassID: TCLSID;
    Unknown: IUnknown;
    l_Result: HResult;
  begin
    Result := False;

    l_Result := CLSIDFromProgID(PWideChar(WideString(ClassName)), ClassID);
    if (l_Result and $80000000) = 0 then
    begin
      l_Result := GetActiveObject(ClassID, nil, Unknown);
      if (l_Result and $80000000) = 0 then
      begin
        l_Result := Unknown.QueryInterface(IDispatch, Ole_Handle);
        if (l_Result and $80000000) = 0 then
          Result := True;
      end;
    end;
  end;

  {创建OLE对象}
  function My_CreateOleObject(const ClassName: string; out Ole_Handle: IDispatch): Boolean;
  var
    ClassID: TCLSID;
    l_Result: HResult;
  begin
    Result := False;

    l_Result := CLSIDFromProgID(PWideChar(WideString(ClassName)), ClassID);
    if (l_Result and $80000000) = 0 then
    begin
      l_Result := CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
        CLSCTX_LOCAL_SERVER, IDispatch, Ole_Handle);
      if (l_Result and $80000000) = 0 then
        Result := True;
    end;
  end;

var
  l_Excel_Handle: IDispatch;
begin
  if FShow_Progress = True then
  begin
    Create_Run_Excel_Form(nil);
    FRun_Excel_Form.Show;
  end;

  if My_GetActiveOleObject('Excel.Application', l_Excel_Handle) = False then
    if My_CreateOleObject('Excel.Application', l_Excel_Handle) = False then
    begin
      FRun_Excel_Form.Free;
      FRun_Excel_Form := nil;

      raise exception.Create('启动Excel失败,可能没有安装Excel!');
      Result := False;
      Exit;
    end;
  FExcel_Handle := l_Excel_Handle;

  if FShow_Progress = True then
  begin
    FRun_Excel_Form.Free;
    FRun_Excel_Form := nil;
  end;
  Result := True;
end;

{插入新的工作博}
function TDBGridExport.New_Workbook: Boolean;
var
  i: Integer;
begin
  Result := True;
  try
    FWorkbook_Handle := FExcel_Handle.Workbooks.Add;
  except
    raise exception.Create('新建Excel工作表出错!');
    Result := False;
    Exit;
  end;

  if FTitle <> '' then
    FWorkbook_Handle.Application.ActiveWindow.Caption := FTitle;
  if FSheetName <> '' then
  begin
    for i := 2 to FWorkbook_Handle.Sheets.Count do
      if FSheetName = FWorkbook_Handle.Sheets[i].Name then
      begin
        raise exception.Create('工作表命名重复!');
        Result := False;
        exit;
      end;
    try
      FWorkbook_Handle.Sheets[1].Name := FSheetName;
    except
      raise exception.Create('工作表命名错误!');
      Result := False;
      exit;
    end;
  end;
end;

{插入数据}
function TDBGridExport.InsertData_To_Excel: Boolean;
var
  i, j, k: Integer;
  data_Str: string;
  Column_name: string;
  Data_Set: TDataSet;

  bookmark: pointer;
  Before_Scroll, Afrer_Scroll: TDataSetNotifyEvent;
begin
  try
    {显示插入进度}
    if FShow_Progress = True then
    begin
      Create_ProgressForm(nil);
      FProgress_Form.Show;
    end;

    {第一行,插入标题}{仅仅插入可见数据}
    j := 1;
    for i := 1 to FDB_Grid.Columns.Count do
      if FDB_Grid.Columns[i - 1].Visible = True then
      begin
        FWorkbook_Handle.WorkSheets[1].Cells[1, j].Value := FDB_Grid.Columns[i - 1].Title.Caption;
        FWorkbook_Handle.WorkSheets[1].Columns[j].ColumnWidth := FDB_Grid.Columns[i - 1].Width div 6;
        j := j + 1
      end;

   {插入DBGrid中的数据}
    Data_Set := FDB_Grid.DataSource.DataSet;
   {记忆当前位置并取消任何事件}
//  new(bookmark);
    bookmark := Data_Set.GetBookmark;

    Data_Set.DisableControls;
    Before_Scroll := Data_Set.BeforeScroll;
    Afrer_Scroll := Data_Set.AfterScroll;
    Data_Set.BeforeScroll := nil;
    Data_Set.AfterScroll := nil;

    if FShow_Progress = True then
    begin
      Data_Set.Last;
      FProgress_Form.Refresh;
      FProgressBar.Max := Data_Set.RecordCount;
    end;

    Data_Set.First;

    k := 2;
    while not Data_Set.Eof do
    begin
      if FShow_Progress = True then
        FProgressBar.Position := k;

      j := 1;
      for i := 1 to FDB_Grid.Columns.Count do
      begin
        if FDB_Grid.Columns[i - 1].Visible = True then
        begin
          Column_name := FDB_Grid.Columns[i - 1].FieldName;
          data_Str := FDB_Grid.Fields[i - 1].DisplayText;
          FWorkbook_Handle.WorkSheets[1].Cells[k, j].Value := data_Str;
          j := j + 1;
        end;
      end;
      k := k + 1;
      Data_Set.Next;
    end;

    {恢复原始事件以及标志位置}
    Data_Set.GotoBookmark(bookmark);
    Data_Set.FreeBookmark(bookmark);
//  dispose(bookmark);
    Data_Set.EnableControls;
    Data_Set.BeforeScroll := Before_Scroll;
    Data_Set.AfterScroll := Afrer_Scroll;

    Result := True;
  finally
    FExcel_Handle.Visible := True;
    FExcel_Handle.Application.ScreenUpdating := True;

    if FShow_Progress = True then
    begin
      FProgress_Form.Free;
      FProgress_Form := nil;
    end;
  end;
end;

{===============================================================================}
{启动Excel时给出进度显示}
procedure TDBGridExport.Create_Run_Excel_Form(AOwner: TComponent);
var
  Panel: TPanel;
  Prompt: TLabel;                                           {提示的标签}
begin
  if assigned(FRun_Excel_Form) then exit;

  FRun_Excel_Form := TForm.Create(AOwner);
  with FRun_Excel_Form do
  begin
    try
      Font.Name := '宋体';                                  {设置字体}
      Font.Size := 9;
      BorderStyle := bsNone;
      Width := 300;
      Height := 100;
      BorderWidth := 2;
      Color := clBlue;
      Position := poScreenCenter;

      Panel := TPanel.Create(FRun_Excel_Form);
      with Panel do
      begin
        Parent := FRun_Excel_Form;
        Align := alClient;
        BevelInner := bvNone;
        BevelOuter := bvRaised;
        Caption := '';
      end;

      Prompt := TLabel.Create(Panel);
      with Prompt do
      begin
        Parent := panel;
        AutoSize := True;
        Left := 25;
        Top := 25;
        Caption := '正在导出数据,请稍候……';
      end;
    except
    end;
  end;
end;


{===============================================================================}
{创建进度显示窗口}
procedure TDBGridExport.Create_ProgressForm(AOwner: TComponent);
var
  Panel: TPanel;
  Prompt: TLabel;                                           {提示的标签}
begin
  if assigned(FProgress_Form) then exit;

  FProgress_Form := TForm.Create(AOwner);
  with FProgress_Form do
  begin
    try
      Font.Name := '宋体';                                  {设置字体}
      Font.Size := 9;
      BorderStyle := bsNone;
      Width := 300;
      Height := 100;
      BorderWidth := 2;
      Color := clBlue;
      Position := poScreenCenter;
      Panel := TPanel.Create(FProgress_Form);
      with Panel do
      begin
        Parent := FProgress_Form;
        Align := alClient;
        BevelInner := bvNone;
        BevelOuter := bvRaised;
        Caption := '';
      end;

      Prompt := TLabel.Create(Panel);
      with Prompt do
      begin
        Parent := panel;
        AutoSize := True;
        Left := 25;
        Top := 25;
        Caption := '正在导出数据,请稍候……';
      end;

      FProgressBar := TProgressBar.Create(panel);
      with FProgressBar do
      begin
        Parent := panel;
        Left := 20;
        Top := 50;
        Height := 18;
        Width := 260;
      end;
    except
    end;
  end;
end;


end.

我们在对日开发中Delphi控制Excel的经验如下:

            Delphi 5 控制Excel

            作者:吴晓勇,孙唏瑜
            时间:2001年11月20日

(一) 使用动态创建的方法

首先创建 Excel 对象,使用ComObj:
var ExcelApp: Variant;
ExcelApp := CreateOleObject( 'Excel.Application' );

1) 显示当前窗口:
ExcelApp.Visible := True;

2) 更改 Excel 标题栏:
ExcelApp.Caption := '应用程序调用 Microsoft Excel';

3) 添加新工作簿:
ExcelApp.WorkBooks.Add;

4) 打开已存在的工作簿:
ExcelApp.WorkBooks.Open( 'C:/Excel/Demo.xls' );

5) 设置第2个工作表为活动工作表:
ExcelApp.WorkSheets[2].Activate;  
或 
ExcelApp.WorksSheets[ 'Sheet2' ].Activate;

6) 给单元格赋值:
ExcelApp.Cells[1,4].Value := '第一行第四列';

7) 设置指定列的宽度(单位:字符个数),以第一列为例:
ExcelApp.ActiveSheet.Columns[1].ColumnsWidth := 5;

8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
ExcelApp.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米

9) 在第8行之前插入分页符:
ExcelApp.WorkSheets[1].Rows[8].PageBreak := 1;

10) 在第8列之前删除分页符:
ExcelApp.ActiveSheet.Columns[4].PageBreak := 0;

11) 指定边框线宽度:
ExcelApp.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
1-左    2-右   3-顶    4-底   5-斜( / )     6-斜( / )

12) 清除第一行第四列单元格公式:
ExcelApp.ActiveSheet.Cells[1,4].ClearContents;

13) 设置第一行字体属性:
ExcelApp.ActiveSheet.Rows[1].Font.Name := '隶书';
ExcelApp.ActiveSheet.Rows[1].Font.Color  := clBlue;
ExcelApp.ActiveSheet.Rows[1].Font.Bold   := True;
ExcelApp.ActiveSheet.Rows[1].Font.UnderLine := True;

14) 进行页面设置:

a.页眉:
    ExcelApp.ActiveSheet.PageSetup.CenterHeader := '报表演示';
b.页脚:
    ExcelApp.ActiveSheet.PageSetup.CenterFooter := '第&P页';
c.页眉到顶端边距2cm:
    ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
d.页脚到底端边距3cm:
    ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
e.顶边距2cm:
    ExcelApp.ActiveSheet.PageSetup.TopMargin := 2/0.035;
f.底边距2cm:
    ExcelApp.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
g.左边距2cm:
    ExcelApp.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
h.右边距2cm:
    ExcelApp.ActiveSheet.PageSetup.RightMargin := 2/0.035;
i.页面水平居中:
    ExcelApp.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
j.页面垂直居中:
    ExcelApp.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
k.打印单元格网线:
    ExcelApp.ActiveSheet.PageSetup.PrintGridLines := True;

15) 拷贝操作:

a.拷贝整个工作表:
    ExcelApp.ActiveSheet.Used.Range.Copy;
b.拷贝指定区域:
    ExcelApp.ActiveSheet.Range[ 'A1:E2' ].Copy;
c.从A1位置开始粘贴:
    ExcelApp.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
d.从文件尾部开始粘贴:
    ExcelApp.ActiveSheet.Range.PasteSpecial;

16) 插入一行或一列:
a. ExcelApp.ActiveSheet.Rows[2].Insert;
b. ExcelApp.ActiveSheet.Columns[1].Insert;

17) 删除一行或一列:
a. ExcelApp.ActiveSheet.Rows[2].Delete;
b. ExcelApp.ActiveSheet.Columns[1].Delete;

18) 打印预览工作表:
ExcelApp.ActiveSheet.PrintPreview;

19) 打印输出工作表:
ExcelApp.ActiveSheet.PrintOut;

20) 工作表保存:
if not ExcelApp.ActiveWorkBook.Saved then
   ExcelApp.ActiveSheet.PrintPreview;

21) 工作表另存为:
ExcelApp.SaveAs( 'C:/Excel/Demo1.xls' );

22) 放弃存盘:
ExcelApp.ActiveWorkBook.Saved := True;

23) 关闭工作簿:
ExcelApp.WorkBooks.Close;

24) 退出 Excel:
ExcelApp.Quit;

(二) 使用Delphi 控件方法
在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。 

1)  打开Excel 
ExcelApplication1.Connect;

2) 显示当前窗口:
ExcelApplication1.Visible[0]:=True;

3) 更改 Excel 标题栏:
ExcelApplication1.Caption := '应用程序调用 Microsoft Excel';

4) 添加新工作簿:
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0));
 
5) 添加新工作表:
var Temp_Worksheet: _WorkSheet;
begin
Temp_Worksheet:=ExcelWorkbook1.
WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet;
ExcelWorkSheet1.ConnectTo(Temp_WorkSheet);
End;
 
6) 打开已存在的工作簿:
ExcelApplication1.Workbooks.Open (c:/a.xls
EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,
    EmptyParam,EmptyParam,EmptyParam,EmptyParam,0)

7) 设置第2个工作表为活动工作表:
ExcelApplication1.WorkSheets[2].Activate;  或
ExcelApplication1.WorksSheets[ 'Sheet2' ].Activate;

8) 给单元格赋值:
ExcelApplication1.Cells[1,4].Value := '第一行第四列';

9) 设置指定列的宽度(单位:字符个数),以第一列为例:
ExcelApplication1.ActiveSheet.Columns[1].ColumnsWidth := 5;

10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
ExcelApplication1.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米

11) 在第8行之前插入分页符:
ExcelApplication1.WorkSheets[1].Rows[8].PageBreak := 1;

12) 在第8列之前删除分页符:
ExcelApplication1.ActiveSheet.Columns[4].PageBreak := 0;

13) 指定边框线宽度:
ExcelApplication1.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
1-左    2-右   3-顶    4-底   5-斜( / )     6-斜( / )

14) 清除第一行第四列单元格公式:
ExcelApplication1.ActiveSheet.Cells[1,4].ClearContents;

15) 设置第一行字体属性:
ExcelApplication1.ActiveSheet.Rows[1].Font.Name := '隶书';
ExcelApplication1.ActiveSheet.Rows[1].Font.Color  := clBlue;
ExcelApplication1.ActiveSheet.Rows[1].Font.Bold   := True;
ExcelApplication1.ActiveSheet.Rows[1].Font.UnderLine := True;

16) 进行页面设置:
 a.页眉:
    ExcelApplication1.ActiveSheet.PageSetup.CenterHeader := '报表演示';
b.页脚:
    ExcelApplication1.ActiveSheet.PageSetup.CenterFooter := '第&P页';
c.页眉到顶端边距2cm:
    ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
d.页脚到底端边距3cm:
    ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
e.顶边距2cm:
    ExcelApplication1.ActiveSheet.PageSetup.TopMargin := 2/0.035;
f.底边距2cm:
    ExcelApplication1.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
g.左边距2cm:
    ExcelApplication1.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
h.右边距2cm:
    ExcelApplication1.ActiveSheet.PageSetup.RightMargin := 2/0.035;
i.页面水平居中:
    ExcelApplication1.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
j.页面垂直居中:
    ExcelApplication1.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
k.打印单元格网线:
    ExcelApplication1.ActiveSheet.PageSetup.PrintGridLines := True;

17) 拷贝操作:

a.拷贝整个工作表:
    ExcelApplication1.ActiveSheet.Used.Range.Copy;

b.拷贝指定区域:
    ExcelApplication1.ActiveSheet.Range[ 'A1:E2' ].Copy;

c.从A1位置开始粘贴:
    ExcelApplication1.ActiveSheet.Range.[ 'A1' ].PasteSpecial;

d.从文件尾部开始粘贴:
    ExcelApplication1.ActiveSheet.Range.PasteSpecial;

18) 插入一行或一列:
a. ExcelApplication1.ActiveSheet.Rows[2].Insert;
b. ExcelApplication1.ActiveSheet.Columns[1].Insert;

19) 删除一行或一列:
a. ExcelApplication1.ActiveSheet.Rows[2].Delete;
b. ExcelApplication1.ActiveSheet.Columns[1].Delete;

20) 打印预览工作表:
ExcelApplication1.ActiveSheet.PrintPreview;

21) 打印输出工作表:
ExcelApplication1.ActiveSheet.PrintOut;

22) 工作表保存:
if not ExcelApplication1.ActiveWorkBook.Saved then
   ExcelApplication1.ActiveSheet.PrintPreview;

23) 工作表另存为:
ExcelApplication1.SaveAs( 'C:/Excel/Demo1.xls' );

24) 放弃存盘:
ExcelApplication1.ActiveWorkBook.Saved := True;

25) 关闭工作簿:
ExcelApplication1.WorkBooks.Close;

26) 退出 Excel:
ExcelApplication1.Quit;
ExcelApplication1.Disconnect;

(三) 使用Delphi 控制Excle二维图
在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet
var asheet1,achart, range:variant;

1)选择当第一个工作薄第一个工作表
asheet1:=ExcelApplication1.Workbooks[1].Worksheets[1];

2)增加一个二维图
achart:=asheet1.chartobjects.add(100,100,200,200);

3)选择二维图的形态
achart.chart.charttype:=4;

4)给二维图赋值
series:=achart.chart.seriescollection;
range:=sheet1!r2c3:r3c9;
series.add(range,true);
 
5)加上二维图的标题
achart.Chart.HasTitle:=True;
achart.Chart.ChartTitle.Characters.Text:=’ Excle二维图’          

6)改变二维图的标题字体大小
achart.Chart.ChartTitle.Font.size:=6;

7)给二维图加下标说明
achart.Chart.Axes(xlCategory, xlPrimary).HasTitle := True;
achart.Chart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text := '下标说明';

8)给二维图加左标说明
achart.Chart.Axes(xlValue, xlPrimary).HasTitle := True;
achart.Chart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text := '左标说明';

9)给二维图加右标说明
achart.Chart.Axes(xlValue, xlSecondary).HasTitle := True;
achart.Chart.Axes(xlValue, xlSecondary).AxisTitle.Characters.Text := '右标说明';

10)改变二维图的显示区大小
achart.Chart.PlotArea.Left := 5;
achart.Chart.PlotArea.Width := 223;
achart.Chart.PlotArea.Height := 108;

11)给二维图坐标轴加上说明
achart.chart.seriescollection[1].NAME:='坐标轴说明';
 
E-Mail: sunxiyu@gd-soft.net
           wuxy@gd-soft.net

声明:转载本文内容请与作者联系。
 
看你是小女子,所以抄來給你
procedure Texportexcel.BitBtn1Click(Sender: TObject);
var
row,column,Tempcolumn:integer;
i,j:integer;
begin
inherited;
ExcelWorksheet1.Disconnect;
ExcelWorkbook1.Disconnect;
ExcelApplication1.Disconnect;
Try
{ExcelWorksheet1.Connect;
ExcelWorkbook1.Connect;
Excelapplication1.Connect; }
{ExcelWorksheet1.Connect;
excelWorkbook1.Connect;
excelapplication1.Connect;}
Except
Messagedlg('沒有安裝Excel!'+chr(13)+
'請聯絡系統管理員安裝該軟件!',mtinformation,[mbok],0);
Abort;
end;
Excelapplication1.Visible[0]:=true;
Excelapplication1.Caption:='數據導出窗口';
Excelapplication1.Workbooks.Add(varNull,0);
Excelworkbook1.ConnectTo(excelapplication1.workbooks[excelapplication1.workbooks.count]);
Excelworksheet1.ConnectTo(excelworkbook1.worksheets[1] as _worksheet);
Excelworksheet1.Cells.Item[1,3]:='TOOLING PROGRESS REPORT';
Excelworksheet1.Cells.Item[2,1]:='Customer:';
Excelworksheet1.Cells.Item[2,3]:=dm.xvalue.fieldbyname('customer').value;
Excelworksheet1.Cells.Item[3,1]:='Cust.No:';
Excelworksheet1.Cells.item[3,3]:=dm.xvalue.fieldbyname('custph').value;
Excelworksheet1.Cells.Item[4,1]:='Description';
Excelworksheet1.Cells.Item[4,3]:=dm.xvalue.fieldbyname('custcpname').value;
Excelworksheet1.Cells.item[5,1]:='RSC No.:';
Excelworksheet1.Cells.Item[5,3]:=dm.xvalue.fieldbyname('rscno').value;
Excelworksheet1.Cells.item[6,1]:='Chinese Description:';
Excelworksheet1.Cells.Item[6,3]:=trim(dm.xvalue.fieldbyname('rsccpname').value);
Excelworksheet1.Cells.Item[7,1]:='Start date:';
Excelworksheet1.Cells.Item[7,3]:=dm.xvalue.fieldbyname('rjdate').value;
Excelworksheet1.Cells.item[8,1]:='Estimate Finish Date:';
Excelworksheet1.Cells.Item[8,3]:=copy(dm.xvalue.fieldbyname('rjoverdate').value,1,10);
Excelworksheet1.Cells.item[9,1]:='Actual Finish Date';
Excelworksheet1.cells.Item[10,1]:='total days:';
Excelworksheet1.Cells.Item[10,3]:=dm.xvalue.fieldbyname('totaldays').value;
Excelworksheet1.cells.item[11,1]:='Progress Per Day:';
Excelworksheet1.Cells.Item[11,3]:=COPY(dm.xvalue.fieldbyname('perday').value,1,4)+'%';
Excelworksheet1.Cells.Item[12,1]:='Date/Time';
EXCELWORKSHEET1.Cells.Item[12,2]:='PLAN(%)';
Excelworksheet1.Cells.Item[12,3]:='ACTUAL(%)';
Excelworksheet1.Cells.Item[12,4]:='GAP';
Excelworksheet1.Cells.Item[12,5]:='WORKING DAYS';
row:=13;
dm.evalue.First ;
While Not (dm.evalue.Eof) do
begin
TempColumn := 0 ;
begin
for Column:=1 to DbGrid1.FieldCount do
if DbGrid1.Columns.Items[Column-1].Visible=True Then
begin
TempColumn:=TempColumn+1;
ExcelWorksheet1.Cells.Item[row,TempColumn]:=DbGrid1.Fields[Column-1].AsString;
end;
end;
dm.evalue.Next;
row:=row + 1;
end;
end;
 
后退
顶部