• C++ builder 操作Excel方法(据网上资料整理)


    c++ builder 操作Excel方法,下面是从网上找到的一些不错的方法,学习一下:

      1 用OLE操作Excel(目前最全的资料)(04.2.19更新)
      2 
      3 本文档部分资料来自互联网,大部分是ccrun(老妖)在Excel中通过录制宏-->察看宏代码-->转为CB代码而来.本文档不断更新中.欢迎大家关注.
      4 
      5 要在应用程序中控制Excel的运行,首先必须在编制自动化客户程序时包含Comobj.hpp
      6 
      7 #include "Comobj.hpp"
      8 
      9 C++ Builder把Excel自动化对象的功能包装在下面的四个Ole Object Class函数中,应用人员可以很方便地进行调用。
     10 
     11 设置对象属性:void        OlePropertySet(属性名,参数……);
     12 
     13 获得对象属性:Variant     OlePropertyGet(属性名,参数……);
     14 
     15 调用对象方法:1) Variant OleFunction(函数名,参数……);
     16 
     17              2) void     OleProcedure(过程名,参数……);
     18 
     19 在程序中可以用宏定义来节省时间:
     20 
     21 #define   PG   OlePropertyGet
     22 
     23 #define   PS   OlePropertySet
     24 
     25 #define   FN   OleFunction
     26 
     27 #define   PR   OleProcedure
     28 
     29 举例:
     30 
     31 ExcelApp.OlePropertyGet("workbooks").OleFunction("Add");
     32 
     33 可写为
     34 
     35 ExcelApp.PG("workbooks").FN("Add");
     36 
     37 C++ Builder中使用OLE控制Excel2000,必须掌握Excel2000的自动化对象及Microsoft Word Visual Basic帮助文件中的关于Excel的对象、方法和属性。对象是一个Excel元素,属性是对象的一个特性或操作的一个方面,方法是对象可以进行的动作。
     38 
     39 首先定义以下几个变量:
     40 
     41 Variant ExcelApp,Workbook1,Sheet1,Range1;
     42 
     43 1、Excel中常用的对象是:Application,Workbooks,Worksheets等。
     44 
     45 ★创建应用对象★
     46 
     47        Variant ExcelApp;
     48 
     49        ExcelApp = Variant::CreateObject ("Excel.Application");
     50 
     51        或者
     52 
     53        ExcelApp = CreateOleObject ("Excel.Application");
     54 
     55 ★创建工作簿对象★
     56 
     57        Variant WorkBook1;
     58 
     59        WorkBook1 = ExcelApp.PG("ActiveWorkBook");
     60 
     61 ★创建工作表对象★
     62 
     63        Variant Sheet1;
     64 
     65        Sheet1 = WorkBook1.PG("ActiveSheet");
     66 
     67 ★创建区域对象★
     68 
     69        Variant Range;
     70 
     71        Range = Sheet1.PG("Range","A1:A10");    
     72 
     73        或者使用
     74 
     75        Excel.Exec(PropertyGet("Range")<<"A1:C1").Exec(Procedure("Select"));
     76 
     77 2、常用的属性操作:
     78 
     79 ★使Excel程序不可见★
     80 
     81        ExcelApp.PS("Visible", (Variant)false);
     82 
     83         
     84 
     85 ★新建EXCEL文件★
     86 
     87     
     88 
     89     ◎ 新建系统模板的工作簿
     90 
     91        ExcelApp.PG("workbooks").FN("Add")      //默认工作簿
     92 
     93        ExcelApp.PG("workbooks").FN("Add", 1)   //单工作表
     94 
     95        ExcelApp.PG("workbooks").FN("Add", 2)   //图表 
     96 
     97        ExcelApp.PG("workbooks").FN("Add", 3)   //宏表 
     98 
     99        ExcelApp.PG("workbooks").FN("Add", 4)   //国际通用宏表
    100 
    101        ExcelApp.PG("workbooks").FN("Add", 5)   //与默认的相同
    102 
    103        ExcelApp.PG("workbooks").FN("Add", 6)   //工作簿且只有一个表
    104 
    105        或者使用ExcelApp的Exec方法
    106 
    107        Excel.Exec(PropertyGet("Workbooks")).Exec(Procedure("Add"));
    108 
    109     ◎ 新建自己创建的模板的工作簿
    110 
    111        ExcelApp.PG("workbooks").FN("Add", "C:\Temp\result.xlt");
    112 
    113         
    114 
    115 ★打开工作簿★
    116 
    117        ExcelApp.PG("workbooks").FN("open", "路径名.xls") 
    118 
    119         
    120 
    121 ★保存工作簿★
    122 
    123        WorkBook1.FN("Save");            //保存工作簿
    124 
    125        WorkBook1.FN("SaveAs", "文件名");//工作簿保存为,路径注意用"\"
    126 
    127         
    128 
    129 ★退出EXCEL★
    130 
    131        ExcelApp.FN ("Quit");
    132 
    133        ExcelApp = Unassigned;
    134 
    135        或者
    136 
    137        ExcelApp.Exec(Procedure("Quit"));
    138 
    139         
    140 
    141 ★操作工作表★
    142 
    143     
    144 
    145     ◎ 选择选择工作表中第一个工作表
    146 
    147        Workbook1.PG("Sheets", 1).PR("Select");
    148 
    149        Sheet1 = Workbook1.PG("ActiveSheet");
    150 
    151     
    152 
    153     ◎ 重命名工作表
    154 
    155        Sheet1.PS("Name", "Sheet的新名字");
    156 
    157     
    158 
    159     ◎ 当前工作簿中的工作表总数
    160 
    161 // 本文转自 C++Builder 研究 - http://www.ccrun.com/article.asp?i=529&d=0iezy5
    162 
    163        int nSheetCount=Workbook1.PG("Sheets").PG("Count");       
    164 
    165         
    166 
    167 ★操作行和列★
    168 
    169    
    170 
    171     ◎ 获取当前工作表中有多少行和多少列:
    172 
    173        Sheet1.PG("UsedRange").PG("Columns").PG("Count"); //列数
    174 
    175        Sheet1.PG("UsedRange").PG("Rows").PG("Count");    //行数
    176 
    177     
    178 
    179     ◎ 设置列宽
    180 
    181        ExcelApp.PG("Columns", 1).PS("ColumnWidth", 22);
    182 
    183        或者
    184 
    185        Range = ExcelApp.PG("Cells", 1, 3);
    186 
    187        Range.PS("ColumnWidth", 22);      
    188 
    189     
    190 
    191     ◎ 设置行高
    192 
    193        ExcelApp.PG("Rows", 2).PS("RowHeight", 25);
    194 
    195        或者
    196 
    197        Range = ExcelApp.PG("Cells", 2, 1);        
    198 
    199        Range.PS("RowHeight", 25);     
    200 
    201     
    202 
    203     ◎ 在工作表最前面插入一行
    204 
    205        Sheet1.PG("Rows", 1).PR("Insert");        
    206 
    207     
    208 
    209     ◎ 删除一行
    210 
    211        ExcelApp.PG("Rows", 2).PR("Delete"); //将第2行删除
    212 
    213        // 本文作者:ccrun ,如转载请保证本文档的完整性,并注明出处。
    214 
    215        // 欢迎光临 C++ Builder 研究 www.ccrun.com
    216 
    217        // 摘自:http://www.ccrun.com/doc/go.asp?id=529
    218 
    219         
    220 
    221 ★操作单元格★
    222 
    223     ◎ 设置单元格字体
    224 
    225         Sheet1.PG("Cells", 1, 1).PG("Font").PS("Name", "隶书"); //字体
    226 
    227         Sheet1.PG("Cells", 2, 3).PG("Font").PS("size", 28);     //大小
    228 
    229         
    230 
    231     ◎ 设置所选区域字体
    232 
    233        Range.PG("Cells").PG("Font").PS("Size", 28);
    234 
    235        Range.PG("Cells").PG("Font").PS("Color", RGB(0, 0, 255));
    236 
    237        其中参数的设置:
    238 
    239        Font   Name : "隶书"               //字体名称
    240 
    241               Size : 12                   //字体大小
    242 
    243              Color : RGB(*,*,*)           //颜色
    244 
    245          Underline : true/false           //下划线
    246 
    247              Italic: true/false           //斜体
    248 
    249     
    250 
    251     ◎ 设置单元格格式为小数百分比
    252 
    253        Sheet1.PG("Cells", 1, 1).PS("NumberFormatLocal", "0.00%");
    254 
    255     ◎ 设定单元格的垂直对齐方式
    256 
    257        Range = ExcelApp.PG("Cells", 3, 4);
    258 
    259        // 1=靠上 2=居中 3=靠下对齐 4=两端对齐 5=分散对齐
    260 
    261        Range.PS("VerticalAlignment", 2);       
    262 
    263     
    264 
    265     ◎ 设定单元格的文本为自动换行
    266 
    267        Range = ExcelApp.PG("Cells", 3, 4);
    268 
    269        Range.PS("WrapText", true);
    270 
    271        
    272 
    273 ★单元格的合并★
    274 
    275     ◎ Range = Sheet1.PG("Range", "A1:A2");          //A1和A2单元格合并
    276 
    277        String strRange = "A" + IntToStr(j) + ":" + "C" + IntToStr(j); //比如:A1:C5
    278 
    279        Range1=Sheet1.PG("Range", strRange.c_str()); //可以用变量控制单元格合并
    280 
    281        Range1.FN("Merge", false);
    282 
    283         
    284 
    285 ★读写单元格★
    286 
    287     ◎ 指定单元格赋值
    288 
    289        String strValue = "abcdefg";
    290 
    291        Sheet1.PG("Cells", 3, 6).PS("Value", strValue.c_str()); 
    292 
    293        Sheet1.PG("Cells", j, 1).PS("Value", "总记录:" + String(j-6));
    294 
    295        或者使用
    296 
    297        Excel.Exec(PropertyGet("Cells")<<1<<3).Exec(PropertySet("Value")<<15);
    298 
    299     ◎ 所选区域单元格赋值
    300 
    301        Range.PG("Cells").PS("Value", 10);    
    302 
    303     ◎ 所选区域行赋值
    304 
    305        Range.PG("Rows",1).PS("Value", 1234); 
    306 
    307     ◎ 工作表列赋值
    308 
    309        Sheet1.PG("Columns",1).PS("Value", 1234);
    310 
    311     ◎ 读取取值语句:
    312 
    313        String strValue = Sheet1.PG("Cells", 3, 5).PG("Value");
    314 
    315 ★窗口属性★
    316 
    317     
    318 
    319     ◎ 显示属性
    320 
    321        ExcelApp.PS("Windowstate", 3);       //最大化显示
    322 
    323               1---------xlNormal            //正常显示
    324 
    325               2---------xlMinimized         //最小化显示
    326 
    327               3---------xlMaximized         //最大化显示
    328 
    329     ◎ 状态栏属性
    330 
    331        ExcelApp.PS("StatusBar", "您好,请您稍等。正在查询!");
    332 
    333        ExcelApp.PS("StatusBar", false);     //还原成默认值
    334 
    335     ◎ 标题属性:
    336 
    337        ExcelApp.PS("Caption", "查询系统");
    338 
    339        
    340 
    341 3、操作图表
    342 
    343     
    344 
    345 ★添加图表
    346 
    347      
    348 
    349      Variant Chart; 
    350 
    351      Chart = ExcelApp.Exec(PropertyGet("Charts")).Exec(Function("Add"));
    352 
    353      ExcelApp.Exec(PropertySet("Visible") << true);
    354 
    355      Chart.Exec(PropertySet("Type") << -4100);
    356 
    357 ★滚动图表
    358 
    359      for(int nRotate=5; nRotate <= 180; nRotate += 5)
    360 
    361      {
    362 
    363           Chart.Exec(PropertySet("Rotation") << nRotate);
    364 
    365      }
    366 
    367      for (int nRotate = 175; nRotate >= 0; nRotate -= 5)
    368 
    369      {
    370 
    371           Chart.Exec(PropertySet("Rotation") << nRotate);
    372 
    373      }
    374 
    375      
    376 
    377 另外,为保证程序能正常运行,需要在程序中判断目标机器是否安装了Office;
    378 
    379 try
    380 
    381 {
    382 
    383     ExcelApp = Variant::CreateObject ("Excel.Application");
    384 
    385 }
    386 
    387 catch(...)
    388 
    389 {
    390 
    391     ShowMessage("运行Excel出错,请确认安装了Office");
    392 
    393     return;
    394 
    395 }
    396 
    397 #include "comobj.hpp"
    398 
    399 //---------------------------------------------------------------------------
    400 
    401 // 对指定Excel文件中的指定列进行排序
    402 
    403 // strExcelFileName : excel文件名
    404 
    405 // nCol : 指定的列号
    406 
    407 // nSortStyle : 1:升序,2:降序
    408 
    409 void SortExcelColumn(String strExcelFileName, int nCol, int nSortStyle)
    410 
    411 {
    412 
    413     Variant vExcelApp, vWorkbook, vRange;
    414 
    415     vExcelApp = Variant::CreateObject("Excel.Application");
    416 
    417     vExcelApp.OlePropertySet("Visible", false);
    418 
    419     vExcelApp.OlePropertyGet("WorkBooks").OleProcedure("Open", strExcelFileName.c_str());
    420 
    421     vWorkbook = vExcelApp.OlePropertyGet("ActiveWorkbook");
    422 
    423     vExcelApp.OlePropertyGet("Columns", nCol).OleProcedure("Select");
    424 
    425     vExcelApp.OlePropertyGet("ActiveSheet").OlePropertyGet("Cells", 1, nCol).OleProcedure("Select");
    426 
    427     vRange = vExcelApp.OlePropertyGet("Selection");
    428 
    429     vRange.Exec(Function("Sort")<<vExcelApp.OlePropertyGet("Selection")<<nSortStyle);
    430 
    431     vWorkbook.OleProcedure("Save");
    432 
    433     vWorkbook.OleProcedure("Close");
    434 
    435     vExcelApp.OleFunction("Quit");
    436 
    437     vWorkbook = Unassigned;
    438 
    439     vExcelApp = Unassigned;
    440 
    441     ShowMessage("ok");
    442 
    443 }
    444 
    445 void __fastcall TForm1::Button1Click(TObject *Sender)
    446 
    447 {
    448 
    449     // 对C:123123.xls文件中第一个Sheet的第四列进行升序排序
    450 
    451     SortExcelColumn("C:\123\123.xls", 4, 1);
    452 
    453 }
    454 
    455 excel打印页面设置
    456 
    457 //excel_app.OlePropertyGet("ActiveWindow").OlePropertySet("DisplayGridlines",False);   //不显示背景的网格线;   
    458 
    459       my_worksheet.OlePropertyGet("PageSetup").OlePropertySet("CenterHorizontally",2/0.035);//页面水平居中:   
    460 
    461       my_worksheet.OlePropertyGet("PageSetup").OlePropertySet("PrintGridLines",true);//打印表格线;   
    462 
    463       my_worksheet.OlePropertyGet("PageSetup").OlePropertySet("Orientation",2);   //Orientation=poLandscape;1;2为横向;   
    464 
    465     
    466 
    467       excel_app.OlePropertyGet("ActiveWindow").OlePropertyGet("SelectedSheets").OleFunction("PrintPreview");//打印预览
    468 
    469 给你个完整的例子:   
    470 
    471     
    472 
    473 #include   "comobj.hpp"   
    474 
    475 void   __fastcall   TForm1::Button1Click(TObject   *Sender)   
    476 
    477 {   
    478 
    479           Variant   vExcelApp,   vSheet;   
    480 
    481           AnsiString   strFileName   =   "C:\123\123.xls";   
    482 
    483           if(!FileExists(strFileName))   
    484 
    485                   return;   
    486 
    487     
    488 
    489           //   启动excel   
    490 
    491           vExcelApp   =   CreateOleObject("Excel.Application");   
    492 
    493           //   使Excel程序不可见   
    494 
    495           vExcelApp.OlePropertySet("Visible",   true);   
    496 
    497           //   打开Excel文档   
    498 
    499           vExcelApp.OlePropertyGet("Workbooks").   
    500 
    501                           OleFunction("Open",   strFileName.c_str());   
    502 
    503           //   获得当前活动的Sheet   
    504 
    505           vSheet   =   vExcelApp.OlePropertyGet("ActiveSheet");   
    506 
    507           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintTitleRows",   "");   
    508 
    509           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintTitleColumns",   "");   
    510 
    511           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintArea",   "");   
    512 
    513           vSheet.OlePropertyGet("PageSetup").OlePropertySet("LeftHeader",   "");   
    514 
    515           vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterHeader",   "");   
    516 
    517           vSheet.OlePropertyGet("PageSetup").OlePropertySet("RightHeader",   "");   
    518 
    519           vSheet.OlePropertyGet("PageSetup").OlePropertySet("LeftFooter",   "");   
    520 
    521           vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterFooter",   "");   
    522 
    523           vSheet.OlePropertyGet("PageSetup").OlePropertySet("RightFooter",   "");   
    524 
    525           vSheet.OlePropertyGet("PageSetup").OlePropertySet("LeftMargin",   0.748031496062992);   
    526 
    527           vSheet.OlePropertyGet("PageSetup").OlePropertySet("RightMargin",   0.748031496062992);   
    528 
    529           vSheet.OlePropertyGet("PageSetup").OlePropertySet("TopMargin",   0.984251968503937);   
    530 
    531           vSheet.OlePropertyGet("PageSetup").OlePropertySet("BottomMargin",   0.984251968503937);   
    532 
    533           vSheet.OlePropertyGet("PageSetup").OlePropertySet("HeaderMargin",   0.511811023622047);   
    534 
    535           vSheet.OlePropertyGet("PageSetup").OlePropertySet("FooterMargin",   0.511811023622047);   
    536 
    537           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintHeadings",   false);   
    538 
    539           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintGridlines",   false);   
    540 
    541           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintComments",   -4142);   //   xlPrintNoComments   
    542 
    543           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintQuality",   600);   
    544 
    545           vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterHorizontally",   true);   
    546 
    547           vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterVertically",   false);   
    548 
    549           vSheet.OlePropertyGet("PageSetup").OlePropertySet("Orientation",   1);   //   xlPortrait   
    550 
    551           vSheet.OlePropertyGet("PageSetup").OlePropertySet("Draft",   false);   
    552 
    553           vSheet.OlePropertyGet("PageSetup").OlePropertySet("PaperSize",   9);   //   xlPaperA4   
    554 
    555           vSheet.OlePropertyGet("PageSetup").OlePropertySet("FirstPageNumber",   -4105);   //   xlAutomatic   
    556 
    557           vSheet.OlePropertyGet("PageSetup").OlePropertySet("Order",   1);   //   xlDownThenOver   
    558 
    559           vSheet.OlePropertyGet("PageSetup").OlePropertySet("BlackAndWhite",   false);   
    560 
    561           vSheet.OlePropertyGet("PageSetup").OlePropertySet("Zoom",   false);   
    562 
    563           vSheet.OlePropertyGet("PageSetup").OlePropertySet("FitToPagesWide",   1);   
    564 
    565           vSheet.OlePropertyGet("PageSetup").OlePropertySet("FitToPagesTall",   1);   
    566 
    567     
    568 
    569           //   保存这个工作簿   
    570 
    571           vExcelApp.OlePropertyGet("ActiveWorkBook").OleProcedure("Save");   
    572 
    573           //   退出Excel程序   
    574 
    575           vExcelApp.OleFunction("Quit");   
    576 
    577           ShowMessage("设置成功!");   
    578 
    579     }

    另一实现:http://bbs.csdn.net/topics/360155474

     1 // Access数据库文件名
     2 String strMdbFile = "D:\ccrun\222.mdb";
     3 // Access数据库中的表名
     4 String strTableName = "t1";
     5 
     6 // Excel文件名
     7 String strXlsFile = "D:\ccrun\222.xls";
     8 // Excel文件中的Sheet名
     9 String strSheetName = "Sheet1";
    10 
    11 // 先连接Access数据库
    12 // 63 63 72 75 6E 2E 63 6F 6D
    13 String strConn = String().sprintf(
    14         TEXT("Provider=Microsoft.Jet.OLEDB.4.0;")
    15         TEXT("Data Source=%s;")
    16         TEXT("Persist Security Info=False"),
    17         strMdbFile.c_str()
    18         );
    19 
    20 ADOConnection1->Connected = false;
    21 ADOConnection1->ConnectionString = strConn;
    22 try
    23 {
    24     ADOConnection1->Connected = true;
    25 }
    26 catch(...)
    27 {
    28     ShowMessage("连接失败!");
    29     return;
    30 }
    31 
    32 // 将Excel文件中的数据导入到Access中
    33 String strSQL = String().sprintf(
    34         TEXT("Insert into [%s] ")
    35         TEXT("SELECT * FROM [Excel 5.0;HDR=NO;DATABASE=%s].[%s$];"),
    36         strTableName.c_str(), strXlsFile.c_str(), strSheetName.c_str()
    37         );
    38 ADOConnection1->Execute(strSQL);

    还有一个也可以参考一下:

    使用方法,把下面的RtpExcel中的RtpExcel.h段存成文件RtpExcel.h,
    RtpExcel.c存成文件RtpExcel.c并保存,加入到C++Builder的工程中即可使用。
    
    /*
    RtpExcel.h
    */
    //---------------------------------------------------------------------------
    #ifndef RptExcelH
    #define RptExcelH
    #include <utilcls.h>
    struct RptPageSetup
    {
            String sLeftHeader;
            String sLeftFooter;
            String sCenterheader;
            String sRightHeader;
            String sRightFooter;
            String sCenterFooter;
    };
    struct RptInf
    {
            RptPageSetup RptPage;
            String tTitle;
            String tFirstRowL;
            String tFirstRowR;
    };
    class CRptExcel
    {
    public:
            CRptExcel();
            ~CRptExcel();
            //从sBeginRow行开始设置数据并初始化边框
            bool SetData(const RptInf& rInf,TDataSet* pSet);
            bool PrintRpt();
    private:
            //初始化应用程序对象
            bool InitApp();
            //设置excel程序对象的可见性
            bool SetAppVisible(bool bVisible);
    
    private:
            bool SetCellBorder();
    
            bool SetInfTable();
            bool SetInfCom();
            bool SetTitle();
            bool SetTopRow();
            bool SetCellValue();
            bool NewWorkBook();
            bool NewExcelApp();
    
    private:
            TDataSet       *m_pSet;
            Variant         m_ExcelApp;
            Variant         m_Sheet;
            Variant         m_WorkBook;
            Variant         m_Range;
            unsigned int    m_RowLast;
            unsigned int    m_RowBegin;
            char            m_cBegin;
            char            m_cEnd;
            unsigned int    m_RowCount;
            unsigned int    m_ColCount;
            String          m_sTitle;
            String          m_sCompanyInf;
            String          m_sA3Content;
            String          m_sLastCol3Content;
            bool            m_bAppRun;
    private:
           String   m_sError;
    };
    //---------------------------------------------------------------------------
    #endif
    
    
    
    //---------------------------------------------------------------------------
    /*
    RptExcel.c
    */
    
    #include <vcl.h>
    #pragma hdrstop
    #include "Excel_2K_SRVR.h"
    
    #include "RptExcel.h"
    CRptExcel::CRptExcel()
    {
            m_pSet=NULL;
            m_bAppRun=false;
    }
    CRptExcel::~CRptExcel()
    {
            if(m_bAppRun)
            {
                    m_ExcelApp.OleFunction ("Quit");
            }
    }
    bool CRptExcel::PrintRpt()
    {
            if(!InitApp()) return false;
            if(!SetCellValue()) return false;
            if(!SetCellBorder()) return false;
            if(!SetTitle()) return false;
            if(!SetInfCom()) return false;
            if(!SetInfTable()) return false;
            if(!SetTopRow()) return false;
            SetAppVisible(true);
            return true;
    }
    bool CRptExcel::InitApp()
    {
            if(!NewExcelApp())      return false;
            if(!NewWorkBook())      return false;
            return true;
    }
    bool CRptExcel::NewExcelApp()
    {
        try
        {
            m_ExcelApp = Variant::CreateObject("excel.application");
            m_bAppRun=true;
        }
        catch(...)
        {
            m_sError="不能初始化Excel应用程序对象!";
            return false;
        }
        return true;
    }
    bool CRptExcel::NewWorkBook()
    {
     Variant all_workbooks;
     //-- Get workbooks collection
     all_workbooks = m_ExcelApp.OlePropertyGet("Workbooks");
     //-- Set number of worksheets to 1
     m_ExcelApp.OlePropertySet("SheetsInNewWorkbook",(Variant)1);
     //-- Create a new workbook
     m_WorkBook=all_workbooks.OleFunction("Add");
            m_Sheet=m_WorkBook.OlePropertyGet("ActiveSheet");
            return true;
    }
    bool CRptExcel::SetAppVisible(bool bVisible)
    {
            m_ExcelApp.OlePropertySet("Visible",(Variant)bVisible);
            return true;
    }
    //得到m_cEnd,m_cBegin;m_RowLast;m_RowBegin;的值
    bool CRptExcel::SetData(const RptInf& rInf,TDataSet* pSet)
    {
            m_ColCount=pSet->FieldCount;
            m_cBegin='A';
            m_cEnd='A'+m_ColCount;
            m_RowBegin=4;
            m_RowCount=pSet->RecordCount;
            m_RowLast=m_RowBegin+m_RowCount;
            m_pSet=pSet;
            m_sTitle=rInf.tTitle;
            m_sA3Content=rInf.tFirstRowL;
            m_sLastCol3Content=rInf.tFirstRowR;
            m_sCompanyInf=rInf.RptPage.sLeftHeader;
            return true;
    }
    bool CRptExcel::SetCellValue()
    {
            char ctemp,cEnd;
            int iRow,iRowLast;
            unsigned int index;
            Variant cell;
            String str;
            if(!m_pSet)
            {
                    m_sError="没有设置数据集!";
                    return false;
            }
            if(m_pSet->Eof&&m_pSet->Bof)
            {
                    m_sError="数据集为空";
                    return false;
            }
            if(m_ColCount<=0)
            {
                    m_sError="列数读取出错!";
                    return false;
            }
            ctemp='A';iRow=4;
            for(index=0;index<m_ColCount;index++)
            {
                    ctemp='A'+index;
                    str.sprintf("%c%d",ctemp,iRow);
                    cell=m_Sheet.OlePropertyGet("Range",str);
                    str=m_pSet->Fields->Fields[index]->FieldName;
                    cell.OlePropertySet("Value",str);
                    if(ctemp=='Z')
                    {
                            m_sError="列数太多出错";
                            return false;
                    }
            }
    
            iRow++;ctemp='A';
            m_pSet->First();
            while(!m_pSet->Eof)
            {
                    for(index=0;index<m_ColCount;index++)
                    {
                            ctemp='A'+index;
                            str.sprintf("%c%d",ctemp,iRow);
                            cell=m_Sheet.OlePropertyGet("Range",str);
                            str=m_pSet->Fields->Fields[index]->AsString;
                            cell.OlePropertySet("Value",str);
                    }
                    iRow++;
                    m_pSet->Next();
            }
    
            return true;
    }
    bool CRptExcel::SetTitle()
    {
            String str;
            char ct;
            str.sprintf("%c%d:%c%d",'A',1,('A'+m_ColCount),1);
            Variant vCell;
            try
            {
            vCell=m_Sheet.OlePropertyGet("Range",str);
            vCell.OlePropertySet("Value",m_sTitle);
            }
            catch(...)
            {
                    m_sError="设置表头信息时出错!";
                    return false;
            }
            return true;
    }
    //设置公司的信息到页眉页脚处
    bool CRptExcel::SetInfCom()
    {
            try{
            Variant PageHeader=m_Sheet.OlePropertyGet("PageSetup");
            PageHeader.OlePropertySet("RightHeader","&D ");
            PageHeader.OlePropertySet("LeftHeader",m_sCompanyInf);
            }
            catch(...)
            {
                    m_sError="设置页眉信息时出错!";
                    return false;
            }
            return true;
    }
    bool CRptExcel::SetInfTable()
    {
    
            try{
            Variant PageHeader=m_Sheet.OlePropertyGet("PageSetup");
            PageHeader.OlePropertySet("RightFoot","&P/&N");
            PageHeader.OlePropertySet("LeftFoot",m_sTitle);
            }
            catch(...)
            {
                    m_sError="设置表头信息时出错!";
                    return false;
            }
            return true;
    }
    bool CRptExcel::SetTopRow()
    {
            try{
            Variant vCell=m_Sheet.OlePropertyGet("Range","A3");
            vCell.OlePropertySet("Value",m_sA3Content);
            String str;
            str.sprintf("%c3",'A'+m_ColCount);
            vCell.OlePropertyGet("Range",str);
            vCell.OlePropertySet("Value",m_sLastCol3Content);
            }
            catch(...)
            {
                    m_sError="设置表头信息时出错!";
                    return false;
            }
            return true;
    }
    bool CRptExcel::SetCellBorder()
    {
            String str;
            char ct='A';
            for(unsigned int index=m_RowBegin;index<m_RowLast+1;index++)
            {
             for(unsigned int j=0;j<m_ColCount;j++)
             {
                  ct='A'+j;
                  Variant vCell,vBorder;
                  try{
                        str.sprintf("%c%d",ct,index);
                        vCell=m_Sheet.OlePropertyGet("Range",str);
                        vCell.OlePropertyGet("Borders").OlePropertySet("linestyle",xlContinuous);
                        if(j==0)//对第一列的单元格设置其左边界为粗
                        {
                                vBorder=vCell.OlePropertyGet("Borders",xlEdgeLeft);
                                vBorder.OlePropertySet("linestyle",xlContinuous);
                                vBorder.OlePropertySet("weight",xlThick);
                        }
                        if(j==m_ColCount-1)//the Right Edge of last col
                        {
                                vBorder=vCell.OlePropertyGet("Borders",xlEdgeRight);
                                vBorder.OlePropertySet("linestyle",xlContinuous);
                                vBorder.OlePropertySet("weight",xlThick);
                        }
                        if(index==m_RowBegin)//the first row having data
                        {
                                vBorder=vCell.OlePropertyGet("Borders",xlEdgeTop);
                                vBorder.OlePropertySet("linestyle",xlContinuous);
                                vBorder.OlePropertySet("weight",xlThick);
                        }
                        if(index==m_RowLast)
                        {
                                vBorder=vCell.OlePropertyGet("Borders",xlEdgeBottom);
                                vBorder.OlePropertySet("linestyle",xlContinuous);
                                vBorder.OlePropertySet("weight",xlThick);
                        }
                    }
                    catch(...)
                    {
                            m_sError="设置边框时出错!";
                            return false;
                    }
             }
            }
            return true;
    }
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
  • 相关阅读:
    SQL server查询笔记
    thinkphp ajax无刷新上传头像
    JSTL
    EL表达式
    jBox 弹框内容交互
    网页可读不可写
    readonly与disable的区别
    vuex 的使用
    页面向上滚动
    按照数组中的对象属性进行排序
  • 原文地址:https://www.cnblogs.com/kernel0815/p/3315893.html
Copyright © 2020-2023  润新知