5,140
社区成员
发帖
与我相关
我的任务
分享
void CtestxlsDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
//获取当前应用程序目录
TCHAR path[MAX_PATH];
CString strPath;
GetModuleFileName(NULL,path,MAX_PATH);
strPath = path;
int nPos = strPath.ReverseFind('\\');
strPath=strPath.Left(nPos+1);
strPath += L"test.xls";
HANDLE hFind;
WIN32_FIND_DATA findData = {0};
hFind=FindFirstFile(strPath,&findData);
if(hFind == INVALID_HANDLE_VALUE)
{
CString TempfileStr;
TempfileStr.Format(L"XLS文件'%s'不存在",strPath);
AfxMessageBox(TempfileStr);
return;
}
//////////////////////////////////////////////////////////////////////////
Excel::_ApplicationPtr pApplication = NULL;
Excel::_WorkbookPtr pThisWorkbook = NULL;
Excel::_WorksheetPtr pThisWorksheet = NULL;
Excel::SheetsPtr pThisSheets = NULL;
Excel::RangePtr pThisRange = NULL;
Excel::ShapesPtr shapes=NULL;
Excel::ShapePtr shape=NULL;
Excel::LinesPtr lines=NULL;
pApplication.CreateInstance("Excel.Application");
pApplication->PutVisible(0,VARIANT_FALSE); //将Excel程序隐藏
pApplication->PutDisplayAlerts(0,VARIANT_FALSE); //不弹出消息框(如果有)
//////////////////////////////////////////////////////////////////////////
pThisWorkbook = pApplication->GetWorkbooks()->Add(_variant_t(strPath)); //读模版
pThisSheets = pThisWorkbook->GetWorksheets();
pThisWorksheet = pThisSheets->GetItem((short)1);
pThisRange = pThisWorksheet->GetRange("A1");
shapes = pThisWorksheet->GetShapes();
lines = pThisWorksheet->Lines();
//////////////////////////////////////////////////////////////////////////
CString Name1,Name2,Name3,tmpStr;
//////////////////////////////////////////////////////////////////////////
shapes->AddShape(msoShapeRectangle,200,100,20,20); //此图形单独,不需要组合
//以下图形为一个整体,需要组合
shape=shapes->AddShape(msoShapeOval,100,100,20,20); //圆
Name1=shape->GetName().GetBSTR();
shape=shapes->AddLine(100,100,120,120); //画线
Name2=shape->GetName().GetBSTR();
shape=shapes->AddLine(120,100,100,120); //画线
Name3=shape->GetName().GetBSTR();
//////////////////////////////////////////////////////////////////////////
//选中上面添加的后三个图形,并实现组合功能
SAFEARRAY* pSafeArray = SafeArrayCreateVectorEx(VT_VARIANT, 1, 3, NULL);
if (pSafeArray)
{
VARIANT* apVariantData;
HRESULT hResult = SafeArrayAccessData(pSafeArray, reinterpret_cast<void**> (&apVariantData));
if (SUCCEEDED(hResult))
{
apVariantData[0].vt = VT_BSTR;
apVariantData[0].bstrVal = SysAllocString(Name1);
apVariantData[1].vt = VT_BSTR;
apVariantData[1].bstrVal = SysAllocString(Name2);
apVariantData[2].vt = VT_BSTR;
apVariantData[2].bstrVal = SysAllocString(Name3);
SafeArrayUnaccessData(pSafeArray);
}
CComVariant rangeIndexes(pSafeArray);
pThisWorksheet->GetShapes()->GetRange(&rangeIndexes)->Group();
SafeArrayDestroy(pSafeArray);
}
//excel中的vba实现代码如下:
//ActiveSheet.Shapes.Range(Array("Oval 2", "Line 3", "Line 4")).Select
//Selection.ShapeRange.Group.Select
//////////////////////////////////////////////////////////////////////////
pApplication->PutDisplayAlerts(0,VARIANT_TRUE); //弹出消息框(如果有)
pApplication->PutVisible(0,VARIANT_TRUE);
}