• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Delphi中使用XlsReadWriteII

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

在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;


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
MATLAB中绘制质点轨迹动图并保存成GIF - 金鸡光明右使发布时间:2022-07-18
下一篇:
Windows安装MATLAB R2018a发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap