delphi读取excel

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.

 

delphi读取excel

上一篇:redhat8 安装 wine


下一篇:C#中?、??与?:的使用