#include "stdafx.h"
#include
HRESULT AutoWrap(const int autoType, VARIANT pvResult, IDispatch *pDisp, LPOLESTR ptName,const int cArgs ...)
{
va_list marker;
va_start(marker, cArgs);//等同於(char)(&cArgs)+4,就是讓指向cArgs的指針指向它後面一個參數
if(!pDisp) {
MessageBox(NULL,_T("空的接口"),_T("提示"),NULL);
_exit(0);
}
// Invoke函數的參數
DISPPARAMS dp = { NULL, NULL, 0, 0 };
DISPID dispidNamed = DISPID_PROPERTYPUT;
DISPID dispID;
HRESULT hr;
hr = pDisp->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID);
if(FAILED(hr))
{
MessageBox(NULL,_T("找不到該函數或屬性"),_T("提示"),NULL);
_exit(0);
return hr;
}
VARIANT pArgs = new VARIANT[cArgs+1];
for(int i=0; i
pArgs[i] = va_arg(marker, VARIANT);//得到第一個參數的值,並讓指針指向第二個參數
}
dp.cArgs = cArgs;
dp.rgvarg = pArgs;
if(autoType & DISPATCH_PROPERTYPUT) {
dp.cNamedArgs = 1;
dp.rgdispidNamedArgs = &dispidNamed;
}
hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, autoType, &dp, pvResult, NULL, NULL);
// DISP_E_BADPARAMCOUNT
va_end(marker);
delete [] pArgs;
return hr;
}
int _tmain(int argc, _TCHAR argv[])
{
CoInitialize(NULL);
CLSID clsid;
HRESULT hr = CLSIDFromProgID(L"Excel.Application",&clsid);
if (FAILED(hr))
{
MessageBox(NULL,_T("獲取CLSID失敗"),_T("提示"),NULL);
return -1;
}
IDispatch* pApp;
hr = CoCreateInstance(clsid,NULL,CLSCTX_LOCAL_SERVER,IID_IDispatch,(void**)&pApp);
if (FAILED(hr))
{
MessageBox(NULL,_T("請檢查是否已安裝Excel"),_T("提示"),NULL);
exit(1);
}
// 設置Application.visible屬性,1為可見,0為不可見
VARIANT pro;
pro.vt = VT_I4;
pro.lVal = 1;
AutoWrap(DISPATCH_PROPERTYPUT, NULL,pApp, L"Visible", 1, pro);
VARIANT result;
VariantInit(&result);
IDispatch* pBooks;
AutoWrap(DISPATCH_PROPERTYGET,&result,pApp,L"Workbooks",0);
pBooks = result.pdispVal;
IDispatch pBook;
VARIANT result1;
AutoWrap(DISPATCH_PROPERTYGET,&result1,pBooks,L"Add",0);
pBook = result1.pdispVal;
VARIANT result2;
IDispatch pSheet;
AutoWrap(DISPATCH_PROPERTYGET,&result2,pApp,L"ActiveSheet",0);
pSheet = result2.pdispVal;
IDispatch* pShapes;
VARIANT result3;
AutoWrap(DISPATCH_PROPERTYGET,&result3,pSheet,L"Shapes",0);
pShapes = result3.pdispVal;
VARIANT param;
param.vt = VT_BSTR;
WCHAR* str = L"E5:J10";
param.bstrVal = SysAllocString(str);
IDispatch* pRange;
VARIANT result4;
AutoWrap(DISPATCH_PROPERTYGET,&result4,pSheet,L"Range",1,param);
pRange = result4.pdispVal;
VARIANT p1,p2,p3,p4,p5;
WCHAR* filename = L"D:\test.jpg";
p1.vt = VT_BSTR;
p1.bstrVal = SysAllocString(filename);
p2.vt = VT_BOOL;
p2.boolVal = FALSE;
p3.vt = VT_BOOL;
p3.boolVal = TRUE;
p4.vt = VT_R4;
p5.vt = VT_R4;
p4.iVal = 100;
p5.iVal = 0;
hr = AutoWrap(DISPATCH_METHOD,NULL,pShapes,L"AddPicture",7,p5,p5,p4,p4,p3,p2,p1);
AutoWrap(DISPATCH_METHOD,NULL,pApp,L"Quit",0);
pShapes->Release();
pRange->Release();
pSheet->Release();
pBook->Release();
pBooks->Release();
pApp->Release();
CoUninitialize();
return 0;
}
這是源代碼。現在可以實現插入圖片,但是是插入的圖片一直是原來的大小,而且位置也無法調整,始終是從A1開始。應該是參數的問題,那麼,addpicture的參數到底應該怎麼填,調試的時候,也沒有任何錯誤,實在是沒有辦法了,求大神幫忙看下!對了,只能使用C++哦~
哈哈,剛剛不小心解決了,我把P4和P5的VT類型換成float類型就好了,真是暈,oleview裡面也沒有參數介紹。