Advertisement
adilima

Create Instance of Excel Application using C++/COM

Mar 9th, 2016
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <objbase.h>
  3.  
  4. /* Compile using:
  5.  * cl.exe /MD main.cpp /link /out:Test1.exe kernel32.lib user32.lib advapi32.lib ole32.lib
  6.  */
  7.  
  8. int main(int argc, char** argv) {
  9.     HRESULT hr = CoInitializeEx(NULL, 0);
  10.     if (FAILED(hr)) {
  11.         fprintf(stderr, "Unable to initialize COM (HRESULT = 0x%X)\n", hr);
  12.         return -1;
  13.     }
  14.    
  15.     /* Will FAILED if you don't have Microsoft Excel installed */
  16.     GUID guid;
  17.     hr = CLSIDFromProgID(L"Excel.Application", &guid);
  18.     if (FAILED(hr)) {
  19.         fprintf(stderr, "Could not get Excel.Application CLSID\nMaybe you don't have Excel installation\nHRESULT = 0x%X\n", hr);
  20.         CoUninitialize();
  21.         return 0;
  22.     }
  23.    
  24.     IDispatch *pDisp = NULL;
  25.     if (FAILED(hr = CoCreateInstance(guid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void**)&pDisp))) {
  26.         fprintf(stderr, "CoCreateInstance() FAILED (HRESULT = 0x%X)\n", hr);
  27.         CoUninitialize();
  28.         return -1;
  29.     }
  30.    
  31.     fprintf(stdout, "Got Microsoft Excel Application instance as IDispatch ( 0x%p )\n", pDisp);
  32.     pDisp->Release();
  33.    
  34.     CoUninitialize();
  35.    
  36.     fprintf(stdout, "operations completed...\n");
  37.     getchar();
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement