How to create an Excel sheet or chart in VC?

VC++操作Excel实例:读写遍历Sheet技巧 Office自动化技术是基于Microsoft Office组件,利用编程语言(如VC++、VB、C#等)调用Office应用程序提供的接口,实现对Office文档的创建、编辑、修改等自动化操作。自动化技术的核心在于通过程序控制Office应用程序来完成一系列任务,大幅减少重复劳动,提高办公效率。Office自动化技术特别适合于需要处理大量数据的场景。例如,在人力资源管理中,可以利用自动化技术快速生成员工信息表格、工资单等文档;在财务领域,可以自动化生成报表和财务分析图表等。 阅读详情

1.  The require files

When you start to program in VC, you must have the lib files of Excel. The next table will show that:

Office Version

Requirement files

Other files

Default Dir

Office 97

Excel8.olb

Excel.exe

C:/program files/MS Office/office

Office 2000

Excel9.olb

Excel.exe

C:/program files/MS Office/office

Office 2002

Excel.exe

 

C:/program files/MS Office/office10

Office XP

Excel.exe

 

C:/program files/MS Office/office10

 

Before you start work, you must be sure that corresponding files are there.

2.  The Excel Object model

Before you start to work, another thing must be known, it is the Excel object model. It tells us that what are included in Excel? Let us go.

2.1.      Basic model

Excel program consists of eight main parts; these are application object, workbooks object, work book object, work sheets object, work sheet object, range object, charts, chart. Next picture describes the relationship of main objects in Excel:

 

Notice: In fact, there are many other objects, but we often use above objects. You can find the MSDN/office development/office XXXX/excel for getting others.

2.2.      Application Object

Application object is defined in Excel type library as _Application class. Application is the Excel itself, the main functions are:

l         The setting and options of Excel application level

l         Some methods which return to top object

We can get Workbooks/workbook object from _Application object like this:

_Application app;

app.get_workbooks ();

2.3.      Workbooks object

Workbooks is the aggregate of all open books. It is container object, the element is workbook object.

The main functions are:

l         Return the workbook object by index.

l         Add a new empty workbook.

l         Open a file, and create a new workbook for this file.

Example:

Workbooks books = app.get_workbooks();

Workbook newBook = books.add(votp);

newBook = books.Open(“.//1.xls”,...);

newBook = books.get_Item(ColVariant((short)1));

2.4.      Workbook Object

Workbook object is a work book. It includes work sheet and chart. The main functions are:

l         Activate a workbook

l         Return a worksheets or charts

l         Return the active sheet

l         Save to file(XLS)

Example:

newBook.Activate();

WorkSheets sheets = newBook.get_WorkSheets();

newBook.get_Charts();

newBook.get_ActiveChart();

newBook.get_ActiveSheet();

2.5.      Worksheets object

Worksheets is a aggregate object too. Every element is worksheet object. In fact, there is a Sheets object, it is aggregate object too, but the element maybe a worksheet object or a chart object.

The main functions are:

l         Add new work sheet

l         Get work sheet by index

Example:

Worksheet sheet = sheets.add(vopt,vopt,vopt,COleVariant((short)1));

sheet = sheets.get_Item(index);

2.6.      Worksheet object

WorkSheet object is a work sheet of Excel. It is the member of Worksheets and sheets.

The main functions are:

l         All operation on work sheet, like password.

l         Return the Range object by cell area.

l         Activate itself

Example:

sheet. Protect();

sheet.put_Name(“My create sheet”);

Ranget oRng =sheet.get_Range(COleVariant(“A1:B3”),vopt);

sheet.Activate();

2.7.      Range object

Range object is a cell, or a row, or a column, or a area (it maybe a cell or some continuous cells), or a 3D area.

The main functions are:

l         Get and set the cells value

l         Get and set the cells formula

l         Offset

l         Union

l         Font, autofit, and so on…

Example:

oRng.get_Value();

oRng.put_Value(COleVariant("Date"));

oRange = oRange.get_Resize(COleVariant((long)20),

                     COleVariant((long)1));

oRange.put_Formula(COleVariant("=C2*0.07"));

2.8.      Charts

Charts is a aggregate object, it includes all charts in workbook, but it doesn’t contain embedded charts.

The main functions are:

l         Get chart by index

l         Add a new chart to workbook

l         Print chart

Example:

Charts charts = newBook.get_Charts();

Charts.get_Item(index);

Chart newChart = charts.add(vopt,vopt,COleVariant((short)1));

2.9.      Chart

Chart represents chart, it can be a embedded chart or a single chart.

The main functions:

l         Set the basic attributes, e.g., name, title, active.

l         Set the chart type

l         Set the chart data source

Example:

newChart.put_Name("My chart");

newChart.put_ChartType((long)xlLineMarkers);

Range oRang;

oRang = newSheet.get_Range(COleVariant("C2:D21"), vOpt);

newChart.SetSourceData(oRang,COleVariant((short)2));

 

2.10. Chart type

 

3.  The step of creating

Now let us start to create a project and write program for creating an Excel sheet and an Excel chart.

We describe that in two steps. The first step is how to import type libraries and what type libraries are imported into project, and the second step is how to code. The second will be described in next section.

3.1.      How and what

What libraries are imported into? Different office version has different type libraries, see above form.

There are some difference of how to import between VC6.0 and VC7.0.

3.1.1.            VC6.0

1.    Create a MFC exe project

2.    Select Menu “View->Class Wizard”

3.    Select option card “Automation->Add Class->from type library”

4.    Select an excel9.olb/excel8.olb/excel.exe file, which often locates under dir C:/Program files/Office/.

5.    Select specified classes, e.g. _Application, Workbooks, _Workbook, Worksheets, _Worksheet, Range, then click OK, and a file named excel9.h/excel8.h will be created. That file includes the definition of above classes.

See next pictures:


Picture 1:


Picture 2:


Picture 3:


Picture 4:


Picture 5:

3.1.2.            VC7.0

1.    Create a MFC EXE project, single document, and container

2.    Select menu “Project->Class Wizard”

3.    Select “Class in type library”

4.    Click “Open” button

5.    Set the source of class as “File”, and select the file.

6.    Select the interfaces that you want to add your project from left list and insert them into right list

7.    Set the import file name (excel.h), then click the “Complete” button.

 

 

See next pictures:


Picture 6:


Picture 7:


Picture 8


Picture 9:

4.  Program with create Excel file

We suppose that all classed are defined in excel.h, so we can use those classes by only including excel.h.

We add two menu items, one for creating specified Excel sheet named ID_NewSheet, the other for creating chart name ID_NewChart.

The steps:

1.    Add two menu items

2.    Add two message map functions for above two menu items

3.    Include excel.h file in the file you define above two message map functions.

4.    Implement the two functions

4.1.      Program with sheet

The next is a way of ID_NewSheet message map function implementation:

//Excel object model

    _Application app;

    Workbooks books;

    _Workbook newBook;

    Worksheets sheets;

    _Worksheet oSheet,firstSheet;

    Charts charts;

    _Chart chart,firstChart;

    Range range;

    Range iCell;

    LPDISPATCH lpDisp;

    COleVariant vResult;

    COleVariant vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

 

    //Create Excel server (start Excel)

    if(!app.CreateDispatch("Excel.Application"))

    {

        AfxMessageBox("Can’t start Excel server! ");

        return;

    }

    app.put_Visible(TRUE); //set Excel visible

    app.put_UserControl(TRUE); //user can operate Excel

 

    //new a book

    books.AttachDispatch(app.get_Workbooks());

    newBook = books.Add(vOpt);

 

    //Get worksheets and get the first worksheet

    sheets = newBook.get_Worksheets();

    oSheet = sheets.get_Item(COleVariant((short)1));

 

    //*** ADD DATA TO THE WORKSHEET

    //Add Headers to Row 1 of the worksheet

    Range oRange;

    oRange = oSheet.get_Range(COleVariant("A1"), vOpt);

    oRange.put_Value2(COleVariant("Date"));

    oRange = oSheet.get_Range(COleVariant("B1"), vOpt);

    oRange.put_Value2(COleVariant("Order #"));

    oRange = oSheet.get_Range(COleVariant("C1"), vOpt);

    oRange.put_Value2(COleVariant("Amount"));

    oRange = oSheet.get_Range(COleVariant("D1"), vOpt);

    oRange.put_Value2(COleVariant("Tax"));

    //Create a safe array that is NUMROWS x 3 --

    //column 1 will contain dates column 2 will contain strings

    //and column 3 will contain numbers

    COleSafeArray sa;

    DWORD dwElements[2];

    dwElements[0]= 20;    //Number of rows

    dwElements[1]= 3;          //Number of columns

    sa.Create(VT_VARIANT, 2, dwElements);

    //Populate the safe array with the data

    long index[2];

    long lRow;

    COleVariant vTemp;

    COleDateTime vDateTime;

    CString s;

    for(lRow=0;lRow<=20-1;lRow++)

    {

        index[0] = lRow;  

        //Fill the first column with dates

        index[1] = 0;

        vDateTime.SetDate(1999, rand()%12, rand()%28);

        sa.PutElement(index, (COleVariant)vDateTime);

        //Fill the second column with strings

        index[1] = 1;

        s.Format("ORDR%d", lRow+1000);

        vTemp = s;

        sa.PutElement(index, vTemp);

        //Fill the third column with numbers

        index[1] = 2;

        vTemp = (long)rand();

        sa.PutElement(index, vTemp);

    }

    //Fill a range, starting at A2 with the data in

    //the safe array

    oRange = oSheet.get_Range(COleVariant("A2"), vOpt);

    oRange = oRange.get_Resize(COleVariant((short)20),

        COleVariant((short)3));

    oRange.put_Value2(sa);

    sa.Detach();

    //*** ADD FORMULAS TO THE WORKSHEET

    //Fill the fourth column with a formula to compute the

    //sales tax. Note that the formula uses a "relative"

    //cell reference so that it fills properly.

    oRange = oSheet.get_Range(COleVariant("D2"), vOpt);

    oRange = oRange.get_Resize(COleVariant((long)20),

        COleVariant((long)1));

    oRange.put_Formula(COleVariant("=C2*0.07"));

    //*** FORMAT THE WORKSHEET

    oRange = oSheet.get_Range(COleVariant("A1"), COleVariant("D1"));

    /*Font oFont = oRange.get_Font();

    oFont.SetBold(COleVariant((short)TRUE));//Apply Bold to Headers*/

    oRange = oRange.get_EntireColumn();

    oRange.AutoFit();                    //AutoFit the columns 1:4

    //Make Excel visible and give the user control

    oSheet.put_Name("My New Sheet");

    newBook.SaveAs(COleVariant("C://mynew.xls"),vOpt,vOpt,

        vOpt,vOpt,vOpt,0,

        vOpt,vOpt,vOpt,vOpt,vOpt);

    newBook.Close (vOpt,COleVariant("C://mynew.xls"/*OutFilename*/),vOpt);

    books.Close();

    app.Quit();

4.2.      Program with chart

The next is a way of ID_NewChart message map function implementation:

//New create Excel object model

    _Application app;

    _Workbook newBook;

    Workbooks books;

    Worksheets sheets;

    _Worksheet newSheet;

    Charts  charts;

    _Chart newChart;

    COleVariant vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

    //Create Excel server (start Excel)

    if(!app.CreateDispatch("Excel.Application"))

    {

        AfxMessageBox("Can’t start Excel server!");

        return;

    }

    //app.put_Visible(true); //set Excel visible

    app.put_UserControl(TRUE); //user can operate Excel

   

    books = app.get_Workbooks();

    newBook=books.Open("C://mynew.xls",vOpt, vOpt, vOpt, vOpt, vOpt,

        vOpt, vOpt, vOpt, vOpt, vOpt,vOpt, vOpt,vOpt,vOpt);

    //newBook = books.Add(vOpt);

    sheets = newBook.get_Sheets();

    newSheet = sheets.get_Item(COleVariant((short)1));

    charts = newBook.get_Charts();

    CString tip;

    //for(;m_chartType<100;m_chartType++)

    {

        try

        {

            if(charts.get_Count()>0)

                charts.Delete();

            newChart = charts.Add(vOpt,vOpt,COleVariant((short)1));

            newChart.put_Name("My chart");

            newChart.put_ChartType((long)xlLineMarkers);

 

            tip.Format("C://mynewchart%d.xls",xlLine);

            //MessageBox(tip);

            Range oRang;

            oRang = newSheet.get_Range(COleVariant("C2:D21"), vOpt);

            newChart.SetSourceData(oRang,COleVariant((short)2));

 

            newChart.put_HasTitle(true);

            ChartTitle oChartTtl = newChart.get_ChartTitle();

            oChartTtl.put_Text("My sample xy-scatter chart");

            newChart.put_HasLegend(false);

           

 

            newBook.SaveAs(COleVariant(tip),vOpt,vOpt,

                vOpt,vOpt,vOpt,0,

                vOpt,vOpt,vOpt,vOpt,vOpt);

 

        }

        catch(...)

        {

            //newBook.Close(vOpt,COleVariant(tip/*OutFilename*/),vOpt);

            //app.Quit();

            //continue;

        }

    }

    //newBook.Close (vOpt,COleVariant(tip/*OutFilename*/),vOpt);

    books.Close();

    app.Quit();

VC++实现Excel读写操作示例教程 COM(Component Object Model)是一种用于构建软件组件的二进制接口标准,广泛应用于Windows平台的开发中。其核心理念是通过定义接口(Interface)实现模块化、可扩展和可重用的软件组件。COM组件通过接口暴露其功能,调用者无需了解组件内部实现细节,只需按照接口规范进行调用即可。COM技术的关键特点包括:接口驱动:所有功能通过接口暴露,接口定义了组件的公共方法和属性。跨语言支持:COM组件可以用不同语言实现,调用者也可以使用不同语言访问。 阅读详情

相关推荐

tabSheet.h tabSheet.cpp

tabSheet.h tabSheet.cpp文件

TabSheet_tabsheet源文件_Tabú_TabSheet_fierce7og_MFCTabcontrol_

tabsheet源文件,用于MFC编程中使用tab control

VC 操纵excel中的图表Chart

VC 通过COM 操纵excel中的图表Chart

VS2010 MFC中对Excel进行读写操作

在MFC对话框中实现Excel的读写操作

TX_TYX的博客 3813

Visual C++基础 - 使用OLE/COM操作Excel

将数据保存至Excel表格中,并操作对应的单元格,比如字体、颜色填充等操作。 详细描述了MFC添加EXCEL的接口以及操作

qq_40896597的博客 5551

mfc对Excel的操作

mfc对Excel的操作:导入数据,导出数据。

Goodenough的博客 5505

MFC vc++6 读写Excel

1.Ctrl+W 执行 ClassWizard 2.Add Class.../From a type Library...Office 目录中,找到你想使用的类型库。(excel.exe)根据需要添加,(可以全部)(2003) 3.包含头文件#include "excel.h" 4.详见msdn:Automating Microsoft Office 97 and Microsoft

.... 1309

graph

这个我自己好像都忘记了,呵呵!好像是引用office的图表控件。 Me.graph1.Object.ChartType = xl3DPie  柱形图 簇状柱形图 xlColumnClustered 三维簇状柱形图 xl3DColumnClustered 堆积柱形图 xlColumnStacked 三维堆积柱形图 xl3DColumnStacked 百分比堆积柱形图 xlColumn

菜鸟路漫漫 987

C++ 操作Excel

预期实现结果: C++可对Excel表精确进行某一行某一列的增加、修改、删除、查询数据 预演环境: Window7+VS2013+office2013(32位)、2010(64位)、2007(64位)2003(64位)+WPS2016(位) 预演方法: 1、 ODBC方式访问 2、 通过解析Excel表格...

weixin_33739627的博客 2018

vs2010写入EXCEL数据(二)

#vs2010写入EXCEL数据(二) 可以更改数据,插入公式,编辑背景颜色,控制格式等 1.2007版本的EXCEL 2.VS2010使用MFC 3.新建一个DLG后,加载各个.h文文件。具体步骤:在vs2010中 项目->添加类->TypeLIb中的MFC类->点击添加->在弹出来的对话框中,选择从以下来源添加类,选注册表->可用的类型库中找到Microsoft ...

qq_38190941的博客 1165

MFC、VC++操作excel后,excel程序进程无法正常退出的非暴力处理方法

1、最low的方式:强制结束进程这种方式简单粗暴,但会存在进程安全问题,及可能引起数据丢失,慎用!!!!2、释放顺序问题与Execl相关的变量在关闭和释放的时候顺序必须正确。比如,要先使用Close(),后使用ReleaseDispatch。顺序尽量做到先 Save—>Colse—>Release;在Release时,我们尽量做到由内到外,Rang—>Sheet—>Sheets—>Book—>Books—>App。

学无止尽,谨言慎行! 2850

简单易用的TabSheet

TabSheet 简单易用的TabSheet类 简单易用的TabSheet

VC选项卡(TabControl)用法的应用实例

VC选项卡(TabControl)用法的简单示例,希望这个简单的小程序能够帮助到你,教会你怎么用TabControl。

vc下读取txt文件中的多个脚底压力数据,并分别创建出bmp位图,还将总的压力求出,显示出总的压力分布图

vc下读取txt文件中的多个脚底压力数据,并分别创建出bmp位图,还将总的压力求出,显示出总的压力分布图

VC C++ 操作 Excel 总结

以前总是再往上找相关的资料,可惜哦..... 不过有一天真的找到了,十分感谢一下博主 http://blog.csdn.net/fullsail/article/details/8449448 首先本人提供的类 都是从别人那里直接拿过来的,然后根据需要自己又改了一些,,, 保留了原作者的所有注释。。。 不废话,下面提供 源代码 首先是 Excel  的导出类 ,Excel9

u010682281的专栏 8139

VC++操作Excel生成饼状图!

因为需要通过MFC实现自动生成Excel文件,并且实现数据饼状图的效果,搜索全网只找到生成柱状图的程序模板,怎么改都会显示错误,后来通过Excel宏的录制和编辑弄明白了饼状图的做法(其他图形类似) chart.ChartWizard(var, // Source. COleVariant((short)62), // Gallery: PIE. co...

gy2481367665的博客 2155

VCOffice自动化开发(三)

  二 EXCEL篇及命名空间说明

透明果冻 4905
下一篇: 远程控制计算机的原理
windcsn
博客等级 码龄24年 50粉丝 94原创
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值