unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComObj, OleServer, Excel2000;

type
  TForm1 = class(TForm)
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure PrintFileDOC(tmpFilename:string);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.PrintFileDOC(tmpFilename: string);
var
  ExcelApp,PageSetup,Excelall : Variant;
begin
  try
    //創建OLE對象EXCEL Application
    ExcelApp:=CreateOleObject('Excel.Application');
    ExcelApp.Visible:=true;         // 顯示Word程式
    ExcelApp.DisplayAlerts:=False;
    ExcelApp.Workbooks.Open(tmpFilename);
    Excelall := ExcelApp.Workbooks.Open(tmpFilename);//可列印全部SHEET
    //ExcelApp.quit;
    //ExcelApp.Select;
    //重新設定最大邊界,避免word跳出訊息
    PageSetup := ExcelApp.ActiveSheet.PageSetup;
    PageSetup.LeftMargin:='0.5';        // 邊際位置-左
    PageSetup.RightMargin:='0.5';       // 邊際位置-右
    PageSetup.TopMargin:= '0.5';        // 邊際位置-上
    PageSetup.BottomMargin:= '0.5';     // 邊際位置-下
    ExcelApp.Save; // 存檔,避免關閉Word又跳出訊息
    try
      Excelall.PrintOut(Copies:=1, Collate:=True, Preview:=True); //列印全部Sheet
      ExcelApp.ActiveSheet.PrintOut(Copies:=1, Collate:=True, Preview:=True);//作用中的sheet帶參數，此為預覽列印
      //sleep(5000);
    finally
      ExcelApp.quit;
      ExcelApp:=Unassigned;                     //釋放VARIANT變量
    end;
  except
    on xErr: Exception do
    begin
      Screen.Cursor := crDefault;
      MessageDlg('您的電腦裡未安裝Microsoft Word。'+#13#10+xErr.Message, mtInformation, [mbOk], 0);
      ExcelApp.Quit;
      //ExcelApp:=Unassigned;                     //釋放VARIANT變量
      Exit;
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
  begin
    PrintFileDOC(OpenDialog1.FileName);
    MessageDlg(OpenDialog1.FileName+' 列印完成', mtInformation, [mbOk, mbNo], 0);
  end else
    MessageDlg('取消列印', mtInformation, [mbOk, mbNo], 0);
end;

end.
