如何通过COM对象读取和写入Excel以及Excel实例手动操作

时间:2016-01-22 07:55:01

标签: c++ excel com

我正在尝试通过COM读写Excel。 同时,我还想手动修改单元格值。 似乎存在访问冲突。 如何检测此冲突并避免/

以下是我的代码示例。 在该示例中,do循环将继续将单元格A1值复制到单元格A2。 当我想在COM运行期间手动修改值A1时,会发生错误并退出程序。

//MicroSoft Office Objects
#import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE12\mso.dll"\
rename("DocumentProperties","DocumentPropertiesXL")\
rename("RGB","RBGXL")

//Microsoft VBA Objects
#import "C:\Program Files (x86)\Common Files\microsoft shared\VBA\VBA6\vbe6ext.olb"

//EXCEL application objects
#import "C:\Program Files (x86)\Microsoft Office\Office12\excel.exe" \
rename("DialogBox","DialogBoxXL") \
rename("RGB","RGBCL") \
rename("DocumentProperties","DocumentPropertiesXL")\
rename("ReplaceText","ReplaceTextXL") \
rename("CopyFile","CopyFileXL") \
exclude("IFont","IPicture") no_dual_interfaces

#include "stdafx.h"

#include <iostream>


int main(int argc, _TCHAR* argv[])
{


    //A try block is used to trap any errors in communication
    try
    {
        //Initialize COM interface
        CoInitialize(NULL);

        Excel::_ApplicationPtr XL;

        //Start the Excel Application
        XL.CreateInstance(L"Excel.Application");

        //Make the Excel Application visible, so that we can see it!
        XL->Visible=true;


        Excel::_WorkbookPtr pWorkbook;
        pWorkbook=XL->Workbooks->Open(L"D:\\test.xls");

        //Get a pointer to the active worksheet     
        Excel::_WorksheetPtr pSheet = pWorkbook->Sheets->Item[L"Sheet1"];

        //Get a pointer to the cells on the active worksheet
        Excel::RangePtr pRange = pSheet->Cells;



        pRange->Item[1][1]=20;

        int a;

        //perform a loop to copy value in A1 to A2
        do
        {
            a=pRange->Item[1][1];
            std::cout<<"a="<<a<<std::endl;
            pRange->Item[2][1]=a;
        }while(a>0);

    }
    //If a communication error is thrown, catch it and complain
    catch(_com_error)
    {
        std::cout<<"COM error "<<std::endl;
    }

    //Finally Uninitialise the COM interface

    CoUninitialize();

    //Finish the C++ program

    return 0;
}

1 个答案:

答案 0 :(得分:0)

我通过直接使用COM而不是OLE解决了这个问题 在阅读了freddie1的文章http://www.cplusplus.com/forum/windows/125996/

之后

非常感谢。