How to automate Excel using MFC and worksheet functions

Excel 数据分析常用函数汇总 很多传统行业的数据分析师只要求掌握 Excel 即可,会 SPSS / SAS 是加分项。哪怕在数据分析岗位很多的互联网行业,Excel 依旧是不可替代的基础工具。Excel 是数据分析最常用、最基础的工具。大量传统行业(商贸、工厂、门店进销存)的数据分析师,熟练掌握 Excel + SQL 就可以完成绝大多数日常工作。对于初学者,不用一上来就啃 Python、R 这类编程语言,Excel 自带的函数、透视表、可视化插件足够支撑大部分统计、核对、报表需求; 阅读详情
 
View products that this article applies to.
Article ID : 178781
Last Review : March 8, 2005
Revision : 4.0
This article was previously published under Q178781
On This Page
 
SUMMARY
 
MORE INFORMATION
 
Steps to Create the Project
 
REFERENCES
SUMMARY
This article describes how to automate Microsoft Excel 97, Microsoft Excel 2000, Microsoft Excel 2002, or Microsoft Excel 2003 by using the Microsoft Foundation Class (MFC) library, version 4.2 (installed with Microsoft Visual C++ versions 5.0 and 6.0). Specifically, this article illustrates how to use worksheet functions provided by an add-in such as the Analysis ToolPak (ATP) and how to use the worksheet formula functions that are built-in to Microsoft Excel.
 Back to the top
 
MORE INFORMATION
You can copy the code in this article to the message handler function of an event defined in an MFC .cpp file. However, the purpose of the code is to illustrate the process of using the IDispatch interfaces and member functions defined in the Excel8.olb for Excel 97, in Excel9.olb for Excel 2000, and in Excel.exe for the Excel 2002 and Excel 2003 type library. The primary benefit comes from reading and understanding the code in the example, so that you can modify the example or write code from scratch to automate a worksheet function in Microsoft Excel using MFC.
 Back to the top
 
Steps to Create the Project
1. Follow steps 1 through 12 in the following Microsoft Knowledge Base article to create a sample project that uses the IDispatch interfaces and member functions defined in the Excel8.olb, or Excel9.olb, or Excel.exe for Excel 2002 and Excel 2003 type library:
178749 (http://support.microsoft.com/kb/178749/EN-US/) How To Create an Automation Project Using MFC and a Type Library 
2. At the top of the AutoProjectDlg.cpp, add the following line:      #include "excel8.h"
                                       
If you are automating Excel 2000, include excel9.h. If you are automating Excel 2002 or Excel 2003, include excel.h
 
 
3. Add the following code to CAutoProjectDlg::OnRun() in the AutoProjectDLG.cpp file: Sample Code:       try
      {
      _Application app;     // app is an _Application object.
      _Workbook book;       // More object declarations.
      _Worksheet sheet;
      Workbooks books;
      Worksheets sheets;
 
      Range range;          // Used for Microsoft Excel 97 components.
      LPDISPATCH lpDisp;    // Often reused variable.
 
      // Common OLE variants. Easy variants to use for calling arguments.
      COleVariant
        covTrue((short)TRUE),
        covFalse((short)FALSE),
        covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
 
      // Start Microsoft Excel, get _Application object,
      // and attach to app object.
      if(!app.CreateDispatch("Excel.Application"))
       {
        AfxMessageBox("Couldn't CreateDispatch() for Excel");
        return;
       }
 
 
      // Set visible.
      app.SetVisible(TRUE);
 
      // Register the Analysis ToolPak.
      CString sAppPath;
 
      sAppPath.Format ("%s//Analysis//Analys32.xll", app.GetLibraryPath());
 
      if(!app.RegisterXLL(sAppPath))
        AfxMessageBox("Didn't register the Analys32.xll");
 
      // Get the Workbooks collection.
      lpDisp = app.GetWorkbooks();     // Get an IDispatch pointer.
      ASSERT(lpDisp);
      books.AttachDispatch(lpDisp);    // Attach the IDispatch pointer
                                       // to the books object.
 
      // Open a new workbook and attach that IDispatch pointer to the
      // Workbook object.
      lpDisp = books.Add( covOptional );
      ASSERT(lpDisp);
      book.AttachDispatch( lpDisp );
 
         // To open an existing workbook, you need to provide all
         // arguments for the Open member function. In the case of
         // Excel 2002 you must provide 16 arguments.
         // However in Excel 2003 you must provide 15 arguments.
         // The code below opens a workbook and adds it to the Workbook's
         // Collection object. It shows 13 arguments, required for Excel
         // 2000.
         // You need to modify the path and file name for your own
         // workbook.
 
      //
      // lpDisp = books.Open("C://Test",     // Test.xls is a workbook.
      // covOptional, covOptional, covOptional, covOptional, covOptional,
      // covOptional, covOptional, covOptional, covOptional, covOptional,
      // covOptional, covOptional );   // Return Workbook's IDispatch
      // pointer.
 
      // Get the Sheets collection and attach the IDispatch pointer to your
      // sheets object.
      lpDisp = book.GetSheets();
      ASSERT(lpDisp);
      sheets.AttachDispatch(lpDisp);
 
      // Get sheet #1 and attach the IDispatch pointer to your sheet
      // object.
      lpDisp = sheets.GetItem( COleVariant((short)(1)) );
                                        //GetItem(const VARIANT &index)
      ASSERT(lpDisp);
      sheet.AttachDispatch(lpDisp);
 
      // Fill range A1 with "1/25/98", the settlement date.
      lpDisp = sheet.GetRange(COleVariant("A1"), COleVariant("A1"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("1/25/98")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("1/25/98")); // Excel 2002 and Excel 2003
 
 
      // Fill range A2 with "11/15/99", the maturity date.
      lpDisp = sheet.GetRange(COleVariant("A2"), COleVariant("A2"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("11/15/99")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("11/15/99")); // Excel 2002 and Excel 2003
 
 
      // Fill range A3 with "2", the frequency for semi-annual interest
      // payments.
      lpDisp = sheet.GetRange(COleVariant("A3"), COleVariant("A3"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("2")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("2")); // Excel 2002 and Excel 2003
 
      // Fill range A4 with 1, the basis (actual/actual).
      lpDisp = sheet.GetRange(COleVariant("A4"), COleVariant("A4"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("1")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("1")); // Excel 2002 and Excel 2003
 
      // Fill range C1 with the formula "=COUPNCD(A1, A2, A3, A4)" and
      // format the cell with a Date type of the Number format.
      lpDisp = sheet.GetRange(COleVariant("C1"), COleVariant("C1"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetNumberFormat(COleVariant("mm/dd/yy"));
      range.SetFormula(COleVariant("=COUPNCD(A1, A2, A3, A4)"));
 
      /* This is an alternative that works without placing variables on
      // the worksheet.
      // The values are arguments contained in the SetFormula() call.
      // range.SetFormula(COleVariant(
                       "=COUPNCD(/"09/15/96/",/"11/15/99/",2,1)"));
      */
 
      // *** The example in this block uses a built-in Microsoft Excel
      // function.
 
      // You do not have to register any add-in to use the built-in
 
      // Microsoft Excel worksheet functions.
      lpDisp = sheet.GetRange(COleVariant("C3"), COleVariant("C3"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetFormula(COleVariant("=SUM(A3, A4)"));
      // or use:
      // range.SetFormula(COleVariant("=SUM(2,1)"));
 
      // *** End of example for built-in function usage.
 
      // Release dispatch pointers.
      range.ReleaseDispatch();
      sheet.ReleaseDispatch();
      // This is not really necessary because
      // the default second parameter of AttachDispatch releases
      // when the current scope is lost.
 
      } // End of processing.
 
        catch(COleException *e)
      {
        char buf[1024];     // For the Try...Catch error message.
        sprintf(buf, "COleException. SCODE: %08lx.", (long)e->m_sc);
        ::MessageBox(NULL, buf, "COleException", MB_SETFOREGROUND | MB_OK);
      }
 
      catch(COleDispatchException *e)
      {
        char buf[1024];     // For the Try...Catch error message.
        sprintf(buf,
               "COleDispatchException. SCODE: %08lx, Description: /"%s/".",
               (long)e->m_wCode,(LPSTR)e->m_strDescription.GetBuffer(512));
        ::MessageBox(NULL, buf, "COleDispatchException",
                           MB_SETFOREGROUND | MB_OK);
      }
 
      catch(...)
      {
        ::MessageBox(NULL, "General Exception caught.", "Catch-All",
                           MB_SETFOREGROUND | MB_OK);
      }
                                       
 
 
 Back to the top
 
REFERENCES
For additional information about the Automation of Office applications, click the article number below to view the article in the Microsoft Knowledge Base:
222101 (http://support.microsoft.com/kb/222101/EN-US/) How To: Find and Use Office Object Model Documentation
 
VC开发知识库文章:How to automate Excel from MFC and Visual C++ How to automate Excel from MFC and Visual C++ 2005 or Visual C++ .NET to fill or obtain data in a range using arrays 立即下载

相关推荐

Golang面试(一)莉莉丝游戏-Golang后端开发-中台部门

莉莉丝游戏-Golang后端开发-中台部门 开场白,双方自我介绍,对方介绍这个岗位情况,erlang语言,全部转向go。 聊项目,介绍IM架构以及使用Go写的服务简介 动态扩容相关问题:平常30万,现在100万,你们现在是如何应对的? 如果让你调整架构实现动态扩容,你会怎么做?回答了kafka,是一种,应该还要使用docker和k8s以及微服务框架等 如果使用kafka,你是如何确保消息有序?回答了redis,好像没回答到那个点 消息发送失败的问题,如何做到消息不丢?回答持久化存储、拉消息和ACK 发送失

xmcy001122的专栏 3899

使用MFC操作EXCEL文件

一、加载 1、 在VC6.0里创建一个MFC工程 2、打开MFCClassWizard窗口(查看—>建立类向导),选择Automation,单击AddClass按钮,选择Froma type library...,弹出文件选择对话框,之后定位到C:\Program Files\MicrosoftOffice\OFFICE11\EXCEL.EXE,在生成类中添加所有的对象(其实添加需要的即可

目前打算换一个工作,有招聘windows c++方向的也欢迎联系,北京、济南 最好 5万+

SAP WM模块配置详解

1.给工厂/存储地点分配仓库编码 功能说明 配置路径 IMG>企业结构>分配>分配后勤执行>给工厂/存储地点分配仓库编码 业务示例 配置步骤 2.定义仓库号码控制参数 功能说明 配置路径 IMG>后勤执行>仓库管理>主数据>主数据>定义仓库号码控制参数 业务示例 配置步骤 3.定义编码范围 功能说明 配置路径 IMG>后勤执行>仓库...

weixin_40672823的博客 2万+

MFC中使用OLE/COM操作EXCEL的方法

使用OLE的方法操作EXCEL,首先计算机必须安装excel,这样才会有接口暴露出来。本次使用大神封装好的类。 excel作为OLE/COM库插件,定义好了各类交互接口,而且这些接口是跨语言的,可以导入这些接口,操作excel,本问主要实现excel的读写,所以需要_Application、Workbooks、_Workbook、Worksheets、_Worksheet、Range这几个接口。

Ezio 6458

OCEAN 电路仿真

介绍利用 Cadence OCEAN 进行电路脚本仿真的方法

weixin_43249158的博客 4401

【STM32】433MHz OOK信号软解码实战:从EV1527协议到嵌入式实现

本文详细介绍了基于STM32微控制器实现433MHz OOK信号软解码的完整实战过程。文章从EV1527协议解析入手,重点阐述了利用STM32的GPIO和定时器进行信号采样、脉宽还原、同步头识别以及数据位判决的核心算法,并提供了对抗无线干扰的容错优化策略,帮助开发者深入理解并掌握低成本无线通信的嵌入式实现方案。

weixin_29299807的博客 783

如何自动化 Excel 使用 MFC 和工作表函数

步骤来创建项目1.请按步骤 1 通过以下 Microsoft 知识库文章文章要创建示例项目使用 IDispatch 接口和 Excel8.olb, Excel 9 .olb 或 Excel.exe 对于 Excel 2002 和 Excel 2003 类型库中定义成员函数中 12: 178749 (http://support.microsoft.com/kb/178749/EN-US/) 如何创建自动化项目使用 MFC 和类型库2.在添加到 AutoProjectDlg.cpp, 顶部添加以下行:#in

Augusdi的专栏 1858

手把手教你复现IEEE 2025高光谱图像盲超分算法DBSR(附开源代码与避坑指南)

本文详细介绍了如何从零复现IEEE 2025高光谱图像盲超分算法DBSR,包括环境配置、数据预处理、核心模块解析、训练策略及常见问题解决方案。特别针对开源代码中的关键步骤和潜在问题提供了实用指南,帮助研究者和开发者高效实现Deep blind super-resolution技术,适用于遥感、医疗等领域的图像增强应用。

weixin_42524708的博客 411

mfc操作excel(excel.CPP)

// Machine generated IDispatch wrapper class(es) created with ClassWizard #include "stdafx.h" #include "excel.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __

yt_geniu的专栏 2014

《YOLO系列模型的多模态项目》配置使用教程(必看内容)

在根目录的文件夹中用于存放的是我已经配置好的一些多模态融合模型,可结合专栏中相应的文章介绍,进一步了解测试其中内容。

Limiiiing的博客 4653

AUTOSAR汽车电子嵌入式编程精讲300篇-基于加密算法的车载CAN总线安全通信

随着科学技术的不断更新和社会文明的不断进步,汽车已经走入寻常百姓家, 成为当代社会必不可少的交通工具。伴随着互联网技术的飞速发展,汽车也不再 是一个简单的交通工具,已经逐渐发展成为一个集出行、通信、娱乐等功能于一 身的综合智能体,进而推动了车联网产业的蓬勃发展。车联网是在传统汽车的框架上安装了传感器、执行器、控制器等分布式和集 中式控制器,使汽车具备环境感知、协同控制、优化执行等功能,并通过网络技 术实现与车外环境的信息共享,给驾驶带来方便的同时也终将成为可以替代人操 作的新一代汽车[1-3]。

getusushu的博客 2590

vc对excel操作

这篇比较全面:Office Automation Using Visual C++  http://support.microsoft.com/kb/196776/EN-US/这篇为具体的示例:How to use MFC to automate Excel and create and format a new workbookhttp://support.microsoft.com/kb/17

cation的专栏 2300

车辆重识别/再辨识数据集: Vehicle Re-ID Datasets Collection

车辆数据库 1.VERI-Wild: A Large Dataset and a New Method for Vehicle Re-Identification in the Wild (2019-CVPR) 数据库名称:VERI-Wild 论文:链接 数据库描述: 车辆图像由一个包含174个摄像机,拍摄范围覆盖超过200平方公里的市区CCTV系统拍摄。摄像机是24小时连续拍摄30天,其长时间的...

AI炼丹师 6855

Excel的三种密码:防看、防存、防乱改,各管各的

你的Excel该用哪种密码?看完这篇就懂了

passneo的博客 176

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

全星FMEA系统深度评测:从Excel地狱到平台化失效分析的工程实践

全星FMEA系统的核心价值不在"表格电子化",而在七步法结构化 + 三大文件联动 + 变更可追溯 + 平台化集成。它不完美——自动化程度有限、对基础数据质量高度依赖、AI能力偏保守。但对于需要"说得清、改得准、审得过"的制造企业,这套取舍是合理的。一句话:它卖的不是FMEA软件,是研发风险的可控性。欢迎评论区交流FMEA系统选型与实施经验,后续可拆解APQP/PPAP联动细节。#FMEA #质量管理 #APQP #IATF16949 #制造业数字化 #技术选型。

2501_90343043的博客 315

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

AI如何批量处理Excel文件? 从数据合并、清洗到自动生成报表,看看 AI Agent 怎么完成任务

对于经常需要处理Excel、CSV等结构化数据的用户,这种方式能够将原本需要手动编写脚本的工作,转化为更自然的任务描述和程序执行流程。例如,“删除重复数据”就不够具体,因为两行数据可能具有相同的部门和产品名称,却对应不同日期和不同订单。“请读取指定文件夹中的销售Excel文件,检查每个文件的字段结构,将日期格式统一,合并有效记录,检查重复数据和空值,按照部门和月份统计销售额,最后输出汇总文件。对于需要处理文档、表格、PPT和资料整理的用户,可以重点考察它在办公任务组织和成果生成方面的实际能力。

kejixinzixun的博客 182

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

跨境电商订单导出CSV用Excel打开手机号变科学计数法的列格式排查

手机号在 Excel 中变科学计数法,多因 CSV 被按数值解析。先看编辑栏判断是显示格式还是精度丢失,再用导入向导指定文本列,并核对源文件与保存后的结果,定位异常发生在哪一层。

2501_90960485的博客 127

向 excel、word、pdf 三种文档中占位符插入数据

【代码】向 excel、word、pdf 三种文档中占位符插入数据。

weixin_45934659的博客 43

Excel 导入后标签全错行:Brady Workstation 先把表头和标签顺序对齐

Excel 数据导入 Brady Workstation 后错行,常与表头、字段映射、导入方式、模板模式和标签顺序有关。文章给出官方操作边界、首尾记录验收和 CSV 检查脚本。

preludecorp的博客 292

跨境电商订单导出CSV用Excel打开后SKU前导零丢失的原因与两种修复方式

解释Excel打开订单CSV后SKU前导零丢失的机制,先教用文本编辑器判断零丢在文件还是打开环节,再给出导入向导指定文本列与先建文本模板两种修复方式及适用边界。

2501_93712812的博客 192

Linux & Vim 中 % 、& 用法

……

u013669912的博客 356
上一篇: Licensing ActiveX Controls
下一篇: How To Use WordBasic Functions in an MFC Automation Client for Word 97, Word 2000, Word 2002, or Word 2003
AIRFLYNET
博客等级 码龄25年 6粉丝 12原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值