Many times you need to direct Office to meet the requirements of the program, for example, you need to write the output data to Word or output to the table Excel. If you understand the file format, you can write directly to the file, but since Office provides COM components, it is of course more convenient.
Below is a function of writing a table to an Excel, first of all, is to find the /office/excel9.olb library in VC-ClassWizard-Automation-AddClass-from A Type Library, then add the following Class.
// Declaration variable
_Application ExcelApp; Workbooks wbsMyBooks; _Workbook wbMyBook; Worksheets wssMysheets; _Worksheet wsMysheet; Range Cells; // choose to save the file char * szFilter = "Excel Files (* xls.) | * .Xls"; CFileDialog dlg (FALSE, "xls", "Report", OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, SZFILTER, NULL; IF (DLG.Domodal () == iDok) {
// Template Excel path strpath = getpath ();
// Save the path strsavePath = DLG.GetPathName (); // Create an Excel 2000 server (started Excel) if (! "ExceLapp.created") {AFXMESSAGEBOX ("Create an Excel Service Failed!"); Return;}
// Make Excel invisible ExcelApp.SetVisible (false); LPDISPATCH lpDisp;. // Often reused variable COleVariant covTrue ((short) TRUE), covFalse ((short) FALSE), covOptional ((long) DISP_E_PARAMNOTFOUND, VT_ERROR); lpDisp = ExcelApp.GetWorkbooks (); // Get an IDispatch pointer ASSERT (lpDisp);. wbsMyBooks.AttachDispatch (lpDisp); // Attach the IDispatch pointer // to the books object strPath = "// Info.xls";. lpDisp = wbsMyBooks.Open (. strPath, // Test.xls is a workbook covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional); // Return Workbook's IDispatch // pointer. wbMyBook.AttachDispatch (lpDisp); lpDisp = wbMyBook.GetSheets (); ASSERT (lpDisp); wssMysheets.AttachDispatch (lpDisp);. // 1 and attach the IDispatch pointer Get sheet # to your sheet // object lpDisp = wssMysheets.GetItem (Colevariant (1))); assert (lpdisp); wsmysheet.attachdispatch (lpdisp); // Write form ncount = preport-> getSize (); cells = wsmysheet.getcells (); // Take a single element collection for (i = 0; i
} WsMysheet.SaveAs (strSavePath, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing); wbsMyBooks.Close (); ExcelApp.Quit (); Cells.ReleaseDispatch (); wsMysheet.ReleaseDispatch (); wssMysheets. ReleaseDispatch (); wbmybook.releaseDispatch (); wbsmybooks.releaseDispatch (); excelapp.releaseDispatch (); afxMessageBox ("Generate Report!");} The whole process is not very complicated, if you need other functions, you can directly view the introduced Several Class's functions, probably know what to do, there are still many Class of Class, and if you carefully study, you can achieve more powerful features.