zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    CSS中各种长度单位总结
    Android中实现双击(多击)事件
    android 文件保存到应用和sd卡中
    在Eclipse中搭建Android开发环境
    算法空间复杂度
    我的Android案例签到日历
    Android使用SDKManager下载SDK速度慢 容易丢包和异常的解决办法
    Android应用系列:仿MIUI的Toast动画效果实现
    Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类
    Android学习笔记之Menu的ShowAsAction属性的设置
  • 原文地址:https://www.cnblogs.com/wjhx/p/1719915.html
Copyright © 2011-2022 走看看