delphi读取excel
2021-03-21 08:26
标签:vat book ant str file ring visible roc eol delphi读取excel 标签:vat book ant str file ring visible roc eol 原文地址:https://www.cnblogs.com/onlyou13/p/11823722.htmlunit 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.