C + + operates PPT via COM interface

Source: Internet
Author: User

I. BACKGROUND notes

In VS Environment, develop C + + code operation PPT, support the modification of PPT template. This includes modifying text labels, charts, and tables. To meet the requirements of most software-generated PPT reports, create PPT templates manually and modify the template data in the program.

Second, the development environment construction

Create a COM interface for PowerPoint and Excel through the VS2012 Class Wizard; Because you need to manipulate the charts in the PPT, and the data in the chart is stored in Excel, you need to modify the data on the chart to generate the COM interface for Excel.

1.1 Entering the Class wizard

1.2 Adding a PowerPoint COM interface

1.3 Adding an Excel COM interface


Select all COM interfaces to generate the interface files.

Third, the definition of PPT file base operation function (header file slightly) 3.1 define PPT Application Base Object
class CPPTObject{public:    CApplication m_PPTApp;    CSlides m_Slides;    CSlide m_curSlide;    CPresentation m_Presentaion;};
3.2 Start the PowerPoint software, call the COM interface to install Office
// 创建PPT应用,启动powerpoint程序。bool CPPTUtil::CreatePPTApplication(){    COleException exception;    str"Powerpoint.Application";    if(!m_pPPTObject->m_PPTApp.CreateDispatch(str, &exception))    {        AfxMessageBox(exception.m_sc, MB_SETFOREGROUND);        returnfalse;    }    m_pPPTObject->m_PPTApp.put_Visible(true);    returntrue;}
3.3 Open the ppt template file. Before modifying the PPT content, open the PPT first.
//Open template ppt. BOOL Cpptutil:: Openppt(CONST STD:: String&Pptpath) {cpresentations Presentations=M_ppptobject -M_pptapp.Get_presentations (); M_ppptobject -M_presentaion=Presentations.Open (CString (Pptpath.C_str ()),0,0,1); M_ppptobject -M_slides=M_ppptobject -M_presentaion.Get_slides ();return true;}
3.4 Save PPT file contents, close file, exit PowerPoint program.
// 关闭PPT,保存数据关闭。bool CPPTUtil::ClosePPT(){    m_pPPTObject->m_Presentaion.Save();    m_pPPTObject->m_Presentaion.Close();    m_pPPTObject->m_PPTApp.Quit();    returntrue;}
3.5 Select the specific PPT slide.
// 选中PPT指定索引的幻灯片。bool CPPTUtil::SelectSlide(long slideIndex){    if> m_pPPTObject->m_Slides.get_Count())    {        returnfalse;    }    m_pPPTObject->= m_pPPTObject->m_Slides.Range(COleVariant(slideIndex));    returntrue;}
Four, modify the text edit box function
//Modify text boxBOOLCpptutil::modifytextbox (Const STD::string& Boxname,Const STD::string& strvalue) {cshapes shapes = m_ppptobject->m_curslide.get_shapes (); for(Longi =1; I <= shapes.get_count (); ++i) {CShape shape (shapes).       Item (COleVariant (i))); CString name = Shape.get_name ();if(Shape.get_type () = = (Long) Office::msotextbox && Name.compare (CString (Boxname.c_str ())) = =0) {Ctextframe textFrame = Shape.get_textframe ();            Ctextrange TextRange = Textframe.get_textrange ();            CString txt = textrange.get_text ();       Textrange.put_text (Strvalue.c_str ()); }    }return true;}

The boxname corresponds to the shape Name in the PPT. This shape name seems to be nowhere to be seen in PowerPoint, and there is no way to modify it. Can only be logged when debugging.

V. Modify the chart function in PPT. The chart template is defined in the PPT and the chart data is modified through the COM interface. 5.1 Define the chart data structure. The data for the chart is stored in Excel.

5.1.1 Defining cell data structures

Ccelldatacom::ccelldatacom (ConstCellvaluetype ValueType,Const STD::string& Strvalue,Const intIRow,Const intIcol) {m_valuetype = ValueType;    M_strvalue = strvalue; M_strpos = indextostring (IRow, icol);}//Get cell value typeCellvaluetype Ccelldatacom::getvaluetype () {returnM_valuetype;}//Get String type valueConst STD::string& Ccelldatacom::getstringvalue () {returnM_strvalue;}//Get integer valueLongCcelldatacom::getlongvalue () {returnAtol (M_strvalue.c_str ());}//Get floating-point type valueDoubleCcelldatacom::getdoublevalue () {returnAtof (M_strvalue.c_str ());}//Get cell location nameConst STD::string& Ccelldatacom::getpos () {returnM_strpos;}//Convert cell coordinates to name stringCString ccelldatacom::indextostring (intRowintCol) {CString strresult;if(Col > -) {Strresult.format (_t ("%c%c%d"),' A '+ (col-1)/ --1,' A '+ (col-1)% -, row); }Else{Strresult.format (_t ("%c%d"),' A '+ (col-1)% -, row); }returnstrresult; }5.1. 2Defining chart Data Structures//Insert a row of recordsvoidCchartdatacom::insertrowdata (Const STD:: list<CCellDataCom>& Lstrowdata) {m_lstvalue.push_back (lstrowdata);}//Get Chart DataConst STD:: List<std::list<CCellDataCom> >& Cchartdatacom::getvalue ()Const{returnM_lstvalue;}
5.2 Modifying chart data functions

Modify a chart

BOOLCpptutil::modifychart (Const STD::string& Chartname,Constcchartdatacom& chartData) {cshapes shapes = m_ppptobject->m_curslide.get_shapes (); for(Longi =1; I <= shapes.get_count (); ++i) {CShape shape (shapes). Item (COleVariant (i)));if(Shape.get_type ()! = (Long) Office::msochart | | Chartname! =STD::string(Shape.get_name (). GetBuffer ())) {Continue; }//Modify chart Data        returnModifychartdata (Shape.get_chart (), chartData); }return false;}//Modify chart DataBOOLCpptutil::modifychartdata (Cchart chart,Constcchartdatacom& chartData) {//Activate the Excel data table of the Chart component to open embedded Excel.Cchartdata Chartdatamodel = Chart.get_chartdata ();    Chartdatamodel.activate ();    CWorkbook WorkBook = Chartdatamodel.get_workbook (); CWorksheets sheets = workbook.get_worksheets ();if(Sheets.get_count () = =0)    {return false; }//Gets the first sheet, and the data for the Chart component is embedded in the first sheet page of Excel. VARIANT Vasheetindex;    VASHEETINDEX.VT = VT_I4; Vasheetindex.lval =1; Cworksheet sheet = sheets.get_item (vasheetindex);BOOLBRet =true;//Loop Modify the data of the cells    Const STD:: List<std::list<CCellDataCom> >& lstvalue = Chartdata.getvalue ();STD:: List<std::list<CCellDataCom> >:: Const_iterator iteralldata = Lstvalue.begin (); for(; Iteralldata! = Lstvalue.end (); ++iteralldata) {STD:: list<CCellDataCom>:: Const_iterator iterrowdata = Iteralldata->begin (); for(; Iterrowdata! = Iteralldata->end (); ++iterrowdata) {BRet = Modifycelldata (sheet, *iterrowdata);if(BRet = =false)            { Break; }        }if(BRet = =false)        { Break; }    }//Close ExcelCApplication0 app0 = Workbook.get_application (); App0.    Quit (); Sleep ( -);returnBRet;}//Modify cell dataBOOLCpptutil::modifycelldata (cworksheet sheet, ccelldatacom celldata) {Const STD::string& cellpos = Celldata.getpos ();    CRange range = Sheet.get_range (COleVariant (Cellpos.c_str ()), COleVariant (Cellpos.c_str ())); colevariant* Polevar = NULL;if(Celldata.getvaluetype () = = Cell_string_type) {Polevar =NewCOleVariant (CString (Celldata.getstringvalue (). C_STR ())); }Else if(Celldata.getvaluetype () = = Cell_long_type) {Polevar =NewCOleVariant (Celldata.getlongvalue ()); }Else if(Celldata.getvaluetype () = = Cell_double_type) {Polevar =NewCOleVariant (Celldata.getdoublevalue ()); }Else{return false; } range.put_value2 (*polevar);DeletePolevar;return true;}
Vi. merging multiple PPT file functions
//merge pptBOOLCpptutil::mergeppt (Const STD::string& Outputpptpath,Const STD:: List<std::string>& Lstmergepptpath) {capplication pptapp; COleException exception;//Open PowerPoint programLPCSTR str ="PowerPoint.Application";if(!pptapp.createdispatch (str, &exception)) {AfxMessageBox (EXCEPTION.M_SC, Mb_setforeground);return false; } pptapp.put_visible (true);//Open output fileCpresentations presentations = Pptapp.get_presentations (); Cpresentation outpresention = presentations. Open (CString (Outputpptpath.c_str ()),0,0,1);//Loop open merge File Insert ppt page    STD:: List<std::string>:: Const_iterator itermergefile = Lstmergepptpath.begin (); for(; Itermergefile! = Lstmergepptpath.end (); ++itermergefile) {Cpresentation mergepresention = presentations. Open (CString (Itermergefile->c_str ()),0,0,1); Cslides mergeslides = Mergepresention.get_slides ();intPagenum = Mergeslides.get_count (); Mergepresention.close ();//merge PPT page signCslides outslides = Outpresention.get_slides (); Outslides.insertfromfile (CString (Itermergefile->c_str ()), Outslides.get_count (),1, pagenum);    } outpresention.save ();    Outpresention.close (); Pptapp.quit ();return true;}

C + + operates PPT via COM interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.