delphi读取excel

Posted onlyou13

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

delphi 读取xml

怎么在delphi中读取Excel数据 转

delphi读取文本问题

delphi创建文件和读取.ini文件怎么写

如何在Delphi导入excel读取excel数据

delphi读取excel