zoukankan      html  css  js  c++  java
  • 在Delphi中通过OLE方式写Excel文件

    报表的打印是每个项目都会遇到的问题。由于报表格式要求五花八门,往往又同时要求打印格式可方便调整。作为一种替代方法,可以将需要打印的报表导出到Excel/Word,打印交给Office去吧。由于Office的普及度较高,用户比较熟悉,也容易接受。

    下面主要是在开发中涉及到的在Delphi中写Excel文件方面的问题,直接用代码行来举例说明。测试所用Excel的版本为9.0,即Excel2000

    1、总的思路是将EXCEL作为一个OLE对象来操作。

    //在单元use部分加上:ComObj, Excel2000,并作如下定义:
    var ExcelApp, Book, Sheet, Range: Variant; 

    2、Excel程序对象的操作/设置
    //创建
    ExcelApp := CreateOleObject( 'Excel.Application' );
    //设置Excel窗口可见
    ExcelApp.Visible := True;
     
    //增加一个工作簿
    ExcelApp.WorkBooks.Add;
    Book := ExcelApp.Workbooks[1];
     
    //增加一个工作表
    Book.Worksheets.Add;
    Sheet := Book.Worksheets[1];
     //保存文件
    Sheet.SaveAs(FileName);
     
    //退出Excel与释出
    if not VarIsEmpty(ExcelApp) then
      ExcelApp.Quit;
    ExcelApp := Unassigned;
     
    3、区域操作/设置
    //引用
    Range := Sheet.Range['A2:B3'];
    //合并
    Range.Merge;
    //赋值
    Range.Value := ''赋值';
    //格式
    Range.NumberFormatLocal := '@';               //数字格式设置为文本
    Range.NumberFormatLocal := 'yyyy-m-d';    //数字格式设置为yyyy-m-d日期
    Range.HorizontalAlignment := xlCenter;       //水平对齐
    Range.VerticalAlignment := xlCenter;            //垂直对齐
    Range.Font.Name := '黑体';                             //字体
    Range.Font.Size := 18;
    Range.Font.Bold := true;
    //边框
    Range.Borders[xlEdgeLeft].LineStyle := xlContinuous;     //左
    Range.Borders[xlEdgeLeft].Weight := xlThin;
    Range.Borders[xlEdgeRight].LineStyle := xlContinuous;  //右
    Range.Borders[xlEdgeRight].Weight := xlThin;
    Range.Borders[xlEdgeTop].LineStyle := xlContinuous;    //上
    Range.Borders[xlEdgeTop].Weight := xlThin;
    Range.Borders[xlEdgeBottom].LineStyle := xlContinuous;         //下
    Range.Borders[xlEdgeBottom].Weight := xlThin;
    Range.Borders[xlInsideHorizontal].LineStyle := xlContinuous;  //内竖
    Range.Borders[xlInsideHorizontal].Weight := xlThin;
    Range.Borders[xlInsideVertical].LineStyle := xlContinuous;      //内横
    Range.Borders[xlInsideVertical].Weight := xlThin;
     
    4、单元格操作/设置
    //单元格采用行、列号引用,设 row、col为行、列号
    //赋值
    Sheet.Cells(row, col) := '赋值';
    //设置格式同区域,改成这样来引用
    Sheet.Cells.Item[row, col].HorizontalAlignment := xlCenter;
     
    5、其它
    //行高、列宽自适应
    Sheet.Cells.Rows.AutoFit;
    Sheet.Cells.Columns.AutoFit;
  • 相关阅读:
    eclipse javaWeb项目如何引入jar包
    Unity3D 批量图片资源导入设置
    WaitForTargetFPS
    自适应分辨率
    UnityException: Texture is not readable
    Unity bundle的制作和使用
    Unity3D之Assetbundle
    Unity使用外部版本控制SVN
    AssetBundle机制相关资料收集
    Assetbundle的杂七杂八
  • 原文地址:https://www.cnblogs.com/railgunman/p/8652281.html
Copyright © 2011-2022 走看看