简体   繁体   English

我如何为我的应用程序创建一个自己的实例excel并使用它?

[英]How I can create for my application one's own instance excel and use it?

How I can create for my application one's own instance excel and use it ? 我如何为我的应用程序创建一个自己的实例excel并使用它? Now I have com error when i call CreateInstance and there is a excel instance in process. 现在我在调用CreateInstance时出现com错误,并且正在进行excel实例。 I want to use for my application the global handler of excel instance and kill it when my application will be close 我想为我的应用程序使用excel实例的全局处理程序,并在我的应用程序关闭时将其终止

Excel allows multiple instances. Excel允许多个实例。 The following code works with multiple instances ( XL , XL1 ). 以下代码适用于多个实例( XLXL1 )。 And it works even if you previously start Excel manually. 即使您以前手动启动Excel也可以使用它。 Would you show a code sample to clarify your question. 您是否会展示代码示例以澄清您的问题。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM