delphi excel 读取和写入

//读excel
function  TForm1.readExcel(fileName :WideString):TStringList;
var
    I, J ,len,ret: Integer;
    MaxRow, MaxCol: Integer;
    List, Strs: TStringList;
    ExcelApp, Sheet: Variant;
    OldTime: TDateTime;
    strChar:WideChar;
    str:WideString;
begin
    ListINFO := TStringList.Create;
    Strs := TStringList.Create;
    // 创建一个excel的ole对象
    ExcelApp := CreateOleObject('Excel.Application');
    try
        // 打开一个excel文件
        ExcelApp.WorkBooks.Open(fileName);
        ListINFO.BeginUpdate;
        try
            // 设置工作区
            ExcelApp.WorkSheets[1].Activate;
            Sheet := ExcelApp.WorkSheets[1];
            // 有数据的区域的行数和列数
            MaxRow := Sheet.UsedRange.Rows.count;
            MaxCol := Sheet.UsedRange.Columns.count;
            for I := 2 to MaxRow do
            begin
                Strs.Clear;
                for J := 1 to MaxCol do
                  begin
                  // 获得excel的数据第i行,第j列单元格内的数据
                  Strs.Add(Sheet.Cells[i,j].Value);
                end;
               ListINFO.Add(Strs.CommaText);
            end;
        finally
            // 关闭工作区
            ExcelApp.WorkBooks.Close;
            ListINFO.EndUpdate;
            end;
    finally
  // 释放ole对象
      ExcelApp.Quit;
      //ListINFO :=List;
      List.Free;
      Strs.Free;
      Result :=ListINFO;
   end;
end;

//写excel
function TForm1.writeExcel(const T,Y,W:Integer):string;
var
    I,J,len,ret: Integer;
    MaxRow, MaxCol: Integer;
    ExcelApp, Sheet,WorkBook: Variant;
    strChar:WideChar;
    str:WideString;
begin
    ExcelApp := CreateOleObject('Excel.Application');
    try
        // 打开一个excel文件
        ExcelApp.WorkBooks.Open('E:\tt.xls');
        try
            // 设置工作区
            ExcelApp.WorkSheets[1].Activate;
            Sheet := ExcelApp.WorkSheets[1];
            ExcelApp.Cells(T,Y):=W.ToString();
        finally
            // 关闭工作区
             ExcelApp.Save;
            ExcelApp.WorkBooks.Close;
            end;
    finally
      ExcelApp.Quit;
      Result :='0';
   end;
end;

猜你喜欢

转载自sunties7.iteye.com/blog/2215746