我如何为我的应用程序创建一个自己的实例excel并使用它?现在我在调用CreateInstance时出现com错误,并且正在进行excel实例。我想在我的应用程序中使用excel实例的全局处理程序,并在我的应用程序关闭时将其终止
答案 0 :(得分:2)
Excel允许多个实例。以下代码适用于多个实例(XL
,XL1
)。即使您以前手动启动Excel也可以使用它。您是否会展示代码示例以澄清您的问题。
#import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE12\mso.dll"
#import "C:\Program Files (x86)\Common Files\microsoft shared\VBA\VBA6\VBE6EXT.OLB"
#import "C:\Program Files (x86)\Microsoft Office\Office12\excel.exe" \
rename("DialogBox","ExcelDialogBox") rename("RGB","ExcelRGB") \
exclude("IFont","IPicture")
#include <stdexcept>
#include <iostream>
int main()
{
CoInitialize(NULL);
try {
Excel::_ApplicationPtr XL, XL1;
HRESULT hr = XL.CreateInstance(L"Excel.Application");
if(FAILED(hr)) {
char msg[1024] = {0};
sprintf(msg, "E: initializing first instance failed: %d", hr);
throw std::runtime_error(msg);
}
Excel::_WorkbookPtr workbook = XL->Workbooks->Add(Excel::xlWorksheet);
Excel::_WorksheetPtr worksheet = XL->ActiveSheet;
worksheet->SaveAs("c:\\test.xls");
hr = XL1.CreateInstance(L"Excel.Application");
if(FAILED(hr)) {
char msg[1024] = {0};
sprintf(msg, "E: initializing second instance failed: %d", hr);
throw std::runtime_error(msg);
}
workbook->Close();
XL->Quit();
XL1->Quit();
}
catch(_com_error &ce)
{
std::cout<<"caught" << std::endl;
// Handle the error
}
CoUninitialize();
system("pause");
return 0;
}