Uses ExcelXP, Vcl.OleServer, Vcl.OleAuto;
//用Delphi组件TExcelApplication的操作方法.
function TFormExcelImport.ActiveExcelFile(const FileName :String): Boolean;
var
i: Integer;
// LCID: Integer;
ExcelApplication1: TExcelApplication;
ExcelWorkbook1: TExcelWorkbook;
ExcelWorksheet1: TExcelWorksheet;
begin
Result := False;
try
ExcelApplication1 := TExcelApplication.Create(Application);
ExcelWorkbook1 := TExcelWorkbook.Create(Application);
ExcelWorksheet1 := TExcelWorksheet.Create(Application);
ExcelApplication1.ConnectKind := ckRunningOrNew;
ExcelApplication1.Connect;
// LCID := GetUserDefaultLCID;
if (ExcelApplication1.Workbooks.Count = 0) then
begin
ExcelApplication1.Visible[0] := False;
ExcelApplication1.Caption := 'HKAClient Loading Microsoft Excel';
end;
// 打开工作簿并关联工作簿变量.
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Open(FileName,
False, True, EmptyParam, EmptyParam, EmptyParam, True, EmptyParam,
EmptyParam, EmptyParam, False, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, 0));
// 关联工作表变量
ExcelWorksheet1.ConnectTo(ExcelWorkbook1.ActiveSheet as _WorkSheet);
ListBoxSheetName.Clear;
for i := 1 to ExcelWorkbook1.Sheets.Count do
begin
ListBoxSheetName.Items.Add((ExcelWorkbook1.Sheets[i] as _WorkSheet).Name);
end;
ExcelWorksheet1.Disconnect;
// ExcelWorkbook1.Disconnect;
ExcelWorkbook1.Close(False, FileName, EmptyParam, 0);
// ExcelApplication1.Workbooks.Close(0); //会关闭所有已经打开的Excel文档.
ExcelApplication1.Disconnect;
if (ExcelApplication1.Workbooks.Count = 0) or
(ExcelApplication1.ConnectKind = ckNewInstance) then
ExcelApplication1.Quit;
Result := True;
finally
ExcelWorksheet1.Free;
ExcelWorkbook1.Free;
ExcelApplication1.Free;
end;
end;
//用ComObj对象.
function TFormExcelImport.OpenExcelFile(const FileName:String): Boolean;
var
ExcelApp: OleVariant;
i: Integer;
begin
Result := False;
ExcelApp := CreateOleObject('Excel.Application');
ExcelApp.Caption := 'HKAClient Loading Microsoft Excel';
ExcelApp.Visible := False;
ExcelApp.Workbooks.Open(FileName);
ListBoxSheetName.Clear;
for i := 1 to ExcelApp.Sheets.Count do
begin
ListBoxSheetName.Items.Add(ExcelApp.ActiveWorkbook.Sheets[i].Name);
end;
ExcelApp.Workbooks.Close;
ExcelApp.Quit;
Result := True;
end;