onlyou13

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
unit uExcelUnit;

interface

uses
  Winapi.Windows, System.SysUtils, System.Variants, System.Classes, System.Win.ComObj;

function OpenExcel(filename: string): Variant;
function ReadCell(excel: Variant; sheetIndex: Integer; row, col: Integer): string;
procedure WriteCell(excel: Variant; sheetIndex: Integer; row, col: Integer; value: string);
procedure CloseExcel(excel: Variant);

function OpenReadExcel(filename: string; sheetIndex, row, col: Integer): string;
function OpenWriteExcel(filename: string; sheetIndex, row, col: Integer; value: string): string;

implementation


function OpenReadExcel(filename: string; sheetIndex, row, col: Integer): string;
var
  excel: Variant;
begin
  excel := OpenExcel(filename);
  try
    Result := ReadCell(excel, sheetIndex, row, col);
  finally
    CloseExcel(excel);
  end;
end;

function OpenWriteExcel(filename: string; sheetIndex, row, col: Integer; value: string): string;
var
  excel: Variant;
begin
  excel := OpenExcel(filename);
  try
    WriteCell(excel, sheetIndex, row, col, value);
  finally
    CloseExcel(excel);
  end;
end;

function OpenExcel(filename: string): Variant;
begin
  Result := CreateOleObject('Excel.Application');
  Result.Visible := True;
  Result.WorkBooks.Open(filename);
  Result.Visible := False;
end;

function ReadCell(excel: Variant; sheetIndex: Integer; row, col: Integer): string;
begin
  excel.WorkSheets[sheetIndex].Activate;
  Result := string(excel.Cells[row, col]);
end;

procedure WriteCell(excel: Variant; sheetIndex: Integer; row, col: Integer; value: string);
begin
  excel.WorkSheets[sheetIndex].Activate;
  excel.Cells[row, col] := value;
  excel.ActiveWorkBook.Save;
end;

procedure CloseExcel(excel: Variant);
begin
  excel.Quit;
end;

end.

 

posted on 2019-11-08 22:43  onlyou13  阅读(326)  评论(0编辑  收藏  举报