Delphi中使用XlsReadWriteII

在Delphi中读取Excel文件,使用CreateOleObject的方式挺讨厌的,一直搞不定,输出了文件之后,总会在系统中打开一个Excel,就算Quit也不行,一个程序中使用的多了,还不定搞出什么事情来。狠狠心找个其它的东西来代替,于是发现了XlsReadWriteII。

使用之后发现这个东西真不错,简单好用。不管是读还是写均轻松搞定。下面是Demo中的代码。

写文件代码,包括对格式的定制:

XLS.Filename := 'FormatSample.xls';

XLS.Clear;
// Add format #0
with XLS.Formats.Add do begin
  FontIndex := XLS.Fonts.AddIndex;
  XLS.Fonts[FontIndex].Name := 'Courier new';
  XLS.Fonts[FontIndex].Size := 14;
  XLS.Fonts[FontIndex].Color := xcRed;
end;

// Add format #1
with XLS.Formats.Add do begin
  FontIndex := XLS.Fonts.AddIndex;
  XLS.Fonts[FontIndex].AssignTFont(Font);
end;

// Add format #2
with XLS.Formats.Add do begin
  FillPatternForeColor := xcLilac;
end;

// Add format #3
with XLS.Formats.Add do begin
  BorderTopColor := xcBlue;
  BorderBottomColor := xcBlue;
  BorderTopStyle := cbsThin;
  BorderBottomStyle := cbsThick;
end;

// Add format #4
// ShortDateFormat is a Delphi global variable for the local date format.
with XLS.Formats.Add do begin
  NumberFormat := ShortDateFormat;
end;

XLS.Sheets[0].WriteString(1,2,0,'Format #0');
XLS.Sheets[0].WriteString(1,3,1,'Format #1');
XLS.Sheets[0].WriteString(1,4,2,'Format #2');
XLS.Sheets[0].WriteString(1,5,3,'Format #3');
XLS.Sheets[0].WriteNumber(1,6,4,Date);

XLS.Write;   //如果需要另存为一个文件,改FileName之后再写一次,如需更改工作簿的名称,设置Sheets[0].Name就可以了。

 

读取文件代码:

var
  Col,Row: integer;
  Sum: double;
begin
  if edFilename.Text = '' then begin
    ShowMessage('Filename is missing');
    Exit;
  end;
  Sum := 0;
  XLS.Filename := edFilename.Text;
  XLS.Read; //此行不能省,否则读取不到数据
  XLS.Sheets[0].LastCol := 255;
  XLS.Sheets[0].LastRow := 65535;
  for Col := XLS.Sheets[0].FirstCol to XLS.Sheets[0].LastCol do begin
    for Row := XLS.Sheets[0].FirstRow to XLS.Sheets[0].LastRow do begin
      if (Row < Grid.RowCount) and (Col < Grid.ColCount) then
        Grid.Cells[Col + 1,Row + 1] := XLS.Sheets[0].AsFmtString[Col,Row];
      if XLS.Sheets[0].CellType[Col,Row] = ctFloat then
        Sum := Sum + XLS.Sheets[0].AsFloat[Col,Row];
    end;
  end;
  lblSum.Caption := Format('The sum of all numeric cells are: %.2f',[Sum]);
  Grid.Invalidate;
end;

posted on 2010-04-25 16:31  龙少爷  阅读(4057)  评论(0编辑  收藏  举报

导航