#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++哦~