如何使用 MFC 建立 Microsoft Excel 圖表

文章翻譯 文章翻譯
文章編號: 178783 - 檢視此文章適用的產品。
全部展開 | 全部摺疊

在此頁中

結論

本文將告訴您如何使用 Microsoft 基礎類別 (MFC) 程式庫安裝有 Microsoft Visual C++ 版本 5.0 及 6.0 4.2 版來自動化 Microsoft Excel,使得它將填入的資料工作表,然後建立圖表。

其他相關資訊

您可以複製本文中的程式碼,訊息處理常式函式的 MFC.cpp 檔中定義的事件。不過,程式碼的目的是要說明使用 IDispatch 介面和成員函式在 Excel 的型別程式庫中定義的程序。主要的好處是來自於閱讀和瞭解程式碼,如此您就可以修改這個範例或來自動化 Microsoft Excel 97、 Excel 2000 或 Excel 2002 從頭撰寫程式碼。

附註自動化 Microsoft Excel 2000 及更新版本:

某些方法和屬性已經變更 Microsoft Excel 2000 及更新版本。如需有關使用 Microsoft Excel 2000 和更新版本的型別程式庫本文所述的程式碼範例的詳細資訊,請參閱 「 Microsoft 知識庫 」 中下列文:
224925資訊: 因為新發行的版本,可能會變更 Office 的型別程式庫

建立專案的步驟

  1. 在 Microsoft Excel 中建立名為 Test.xls 的新活頁簿,並將它儲存於根目錄的磁碟機 C。
  2. 請遵循步驟 1 到下列微軟知識庫文件若要建立使用 IDispatch 介面和成員函式在 Excel 的型別程式庫中定義的範例專案的 12:
    178749如何建立使用 MFC 和型別程式庫的自動化專案
  3. [AutoProjectDlg.cpp 頂端加入下列行:
          #include "excel8.h" // excel9.h for Excel 2000, excel.h for Excel 2002
    					
  4. 將下列程式碼加入至 CAutoProjectDlg::OnRun() AutoProjectDLG.cpp 檔案中。

    範例程式碼

          try
          {
           _Application app;  // app is the Excel _Application object.
           _Workbook book;
           _Worksheet sheet;
           _Chart chart;
    
           Workbooks books;
           Worksheets sheets;
           Range range;
           ChartObjects chartobjects;
           Charts charts;
           LPDISPATCH lpDisp;
    
           // Common OLE variants. These are easy variants to use for
           // calling arguments.
           COleVariant
                      covTrue((short)TRUE),
                      covFalse((short)FALSE),
                      covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    
           // Start Excel and get the Application object.
           if(!app.CreateDispatch("Excel.Application"))
           {
            AfxMessageBox(
                 "Couldn't start Excel and get an application 0bject");
            return;
           }
    
           // Set visible.
           app.SetVisible(TRUE);
    
           // Get Workbooks collection.
           lpDisp = app.GetWorkbooks();  // Get an IDispatch pointer.
           ASSERT(lpDisp);
           books.AttachDispatch( lpDisp );  // Attach the IDispatch pointer
                                            // to the books object.
              // Open a workbook.
              lpDisp = books.Open("C:\\Test",
                          covOptional, covOptional, covOptional, covOptional,
                          covOptional, covOptional, covOptional, covOptional,
                          covOptional, covOptional, covOptional, covOptional,
                          covOptional, covOptional, covOptional); // Excel 2000 requires only 13 arguments
              ASSERT(lpDisp);  // It should have worked.
    
           // Attach to a Workbook object.
           book.AttachDispatch( lpDisp );  // Attach the IDispatch pointer
                                           // to the Workbook object.
    
           // Get sheets.
           lpDisp = book.GetSheets();
           ASSERT(lpDisp);
           sheets.AttachDispatch(lpDisp);
    
           lpDisp = sheets.GetItem( COleVariant((short)(1)) );
           ASSERT(lpDisp);
    
           // Attach the lpDisp pointer to a Worksheet object.
           sheet.AttachDispatch(lpDisp);
    
           lpDisp = sheet.GetRange(COleVariant("A1"), COleVariant("W40"));
                                   // The range is from A1 to W40.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);  // Attach the IDispatch pointer
                                          // to the range object.
           range.Clear();  // Could be ClearContents().
    
           ::Sleep(500); // So you can see it happen.
    
           lpDisp = sheet.GetRange(COleVariant("A3"), COleVariant("A3"));
                                                     // From A3 to A3.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);  // Attach the IDispatch pointer
                                          // the range object.
           range.SetValue(COleVariant("March")); // Excel 97 & Excel 2000.
    
    range.SetValue2(COleVariant("March")); // Insert March into range.
    
    
           // Following is a series of repetitive steps to populate the
           // worksheet's cells with a series of Months and values to be
           // used in the Chart object, which is yet to be constructed.
    
           lpDisp = sheet.GetRange(COleVariant("B3"), COleVariant("B3"));
    
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("12")); // 97 & 2000
    
    range.SetValue2(COleVariant("12")); //  Value for March.
    
    
           lpDisp = sheet.GetRange(COleVariant("A4"), COleVariant("A4"));
                // Months will be in column A, values in column B.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("April"));// Excel 97 & Excel 2000
    
    range.SetValue2(COleVariant("April")); // Excel 2002
    
    
           lpDisp = sheet.GetRange(COleVariant("B4"), COleVariant("B4"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("8")); // Excel 97 & Excel 2000
    
    range.SetValue2(COleVariant("8")); // Excel 2002
    
           lpDisp = sheet.GetRange(COleVariant("A5"), COleVariant("A5"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("May"));
    
    range.SetValue2(COleVariant("May"));
    
           lpDisp = sheet.GetRange(COleVariant("B5"), COleVariant("B5"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("2"));
    
    range.SetValue2(COleVariant("2"));
    
           lpDisp = sheet.GetRange(COleVariant("A6"), COleVariant("A6"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("June"));
    
    range.SetValue2(COleVariant("June"));
    
           lpDisp = sheet.GetRange(COleVariant("B6"), COleVariant("B6"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("11"));
    
    range.SetValue2(COleVariant("11"));
    
           lpDisp = sheet.GetRange(COleVariant("A7"), COleVariant("A7"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("July"));
    
    range.SetValue2(COleVariant("July"));
    
           lpDisp = sheet.GetRange(COleVariant("B7"), COleVariant("B7"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("16"));
    
    range.SetValue2(COleVariant("16"));
    
           // The cells are populated. To start the chart,
           // declare some long variables and site the chart.
           long left, top, width, height;
           left = 100;
           top = 10;
           width = 350;
           height = 250;
    
           lpDisp = sheet.ChartObjects(covOptional);
    
           ASSERT(lpDisp);
           chartobjects.AttachDispatch(lpDisp); // Attach the lpDisp pointer
                                      // for ChartObjects to the chartobjects
                                      // object.
           ChartObject chartobject = chartobjects.Add(left, top, width, height); 
                                    //defines the rectangle, 
                                    // adds a new chart at that rectangle and 
                                    // assigns its object reference to a 
                                    // ChartObject variable named chartobject
           chart.AttachDispatch(chartobject.GetChart()); // GetChart() returns
                                             // LPDISPATCH, and this attaches 
                                             // it to your chart object.
    
           lpDisp = sheet.GetRange(COleVariant("A3"), COleVariant("B7"));
                             // The range containing the data to be charted.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
    
           VARIANT var; // ChartWizard needs a Variant for the Source range.
           var.vt = VT_DISPATCH; // .vt is the usable member of the tagVARIANT
                                 // Struct. Its value is a union of options.
           var.pdispVal = lpDisp; // Assign IDispatch pointer
                                  // of the Source range to var.
    
           chart.ChartWizard(var,                    // Source.
                            COleVariant((short)11),  // Gallery: 3d Column.
                            covOptional,             // Format, use default.
                            COleVariant((short)1),   // PlotBy: xlRows.
                            COleVariant((short)0),   // CategoryLabels.
                            COleVariant((short)1),   // SeriesLabels.
                            COleVariant((short)TRUE),  // HasLegend.
                            COleVariant("Use by Month"),  // Title.
                            COleVariant("Month"),    // CategoryTitle.
                            COleVariant("Usage in Thousands"),  // ValueTitles.
                            covOptional              // ExtraTitle.
                            );
           // The return is void.
           ::Sleep(3000);
           chartobject.Delete();  // Removes the first chartobject, sets the
           // ChartObjects.Item() count to 0. The next chart will restore the
           // item count to 1.
           ::Sleep(3000);  // Set the selected range to be erased.
           range.Clear();  // Erase the usage data.
    
           // Beginning of chart 2.
           lpDisp = sheet.GetRange(COleVariant("B3"), COleVariant("B3"));
                                          // From B3 to B3.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);  // Attach the IDispatch pointer
                                          // to the range object.
           range.SetValue(COleVariant("Chocolate")); // Insert Chocolate into
                                                     // the range object.
    range.SetValue2(COleVariant("Chocolate")); // Insert Chocolate
    
           // Following is a series of repetitive steps to populate the
           // worksheet's cells with a series of Flavors and values to be
           // used in the chart object, your second chart.
    
           lpDisp = sheet.GetRange(COleVariant("B4"), COleVariant("B4"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("12")); // Value for Chocolate.
    
    range.SetValue2(COleVariant("12")); // Value for Chocolate.
    
           lpDisp = sheet.GetRange(COleVariant("C3"), COleVariant("C3"));
                // Flavors will be in row 3, values in row 4.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("Vanilla"));
    
    range.SetValue2(COleVariant("Vanilla"));
    
           lpDisp = sheet.GetRange(COleVariant("C4"), COleVariant("C4"));
    
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("8"));
    
    range.SetValue2(COleVariant("8"));
    
           lpDisp = sheet.GetRange(COleVariant("D3"), COleVariant("D3"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("Orange"));
    
    range.SetValue2(COleVariant("Orange"));
    
           lpDisp = sheet.GetRange(COleVariant("D4"), COleVariant("D4"));
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
           range.SetValue(COleVariant("6"));
    
    range.SetValue2(COleVariant("6"));
    
           // The cells are populated. To start the chart,
           // define the bounds, and site the chart.
    
           left = 250;
           top = 40;
           width = 300;
    
           height = 300;
    
           lpDisp = sheet.ChartObjects(covOptional);
    
           ASSERT(lpDisp);
           chartobjects.AttachDispatch(lpDisp); // Attach the lpDisp pointer
                                       // for ChartObjects to the chartobjects
                                       // object.
           chartobjects.Add(left, top, width, height); // Adds 1 to item count.
    
           //**************************************
           lpDisp = chartobjects.Item( COleVariant((short)(1)) );  // It was
               // zero, but just added one at a new location,
               // with new left, top, width, and height.
           ASSERT(lpDisp);
           chartobject.AttachDispatch(lpDisp); // Use definition of new chart
                                               // site.
           chart.AttachDispatch(chartobject.GetChart());
           //**************************************
    
           lpDisp = sheet.GetRange(COleVariant("B3"), COleVariant("D4"));
                             // Range containing the data to be charted.
           ASSERT(lpDisp);
           range.AttachDispatch(lpDisp);
    
           var.pdispVal = lpDisp; // Contains IDispatch pointer
                                  // to the Source range.
    
           chart.ChartWizard(var,                    // Source.
                            COleVariant((short)11),  // Gallery = 3D Column.
                            covOptional,             // Format, use default.
                            COleVariant((short)2),   // PlotBy xlColumns.
                            COleVariant((short)0),   // CategoryLabels.
                            COleVariant((short)1),   // SeriesLabels.
                            COleVariant((short)TRUE),  // HasLegend.
                            COleVariant("Use by Flavor"),  // Title.
                            COleVariant("Flavor"),    // CategoryTitle.
                            COleVariant("Usage in Barrells"),  // ValueTitles.
                            covOptional              // ExtraTitle.
                            );
           // The return is void.
           ::Sleep(3000);
    
           //Show the chart in Print Preview.
           chart.PrintOut(COleVariant((short)1),     // From (page #).
                          COleVariant((short)1),     // To (page #).
                          COleVariant((short)1),     // Copies.
                          COleVariant((short)TRUE),  // Preview.
                          covOptional,               // ActivePrinter.
                          covFalse,                  // PrintToFile.
                          covFalse                   // Collate.
                          covOptional                // PrToFileName // 2002 only
                          );
    
           book.SetSaved(TRUE); // Avoids the 'Save changes?' dialog box.
           app.Quit(); // Excel departs.
    
           // By default, the pointer references for the objects
           // range, book, chart, chartobjects, sheet, and app
           // are automatically released when they go out of scope.
           // ReleaseDispatch()s are unnecessary.
    
           ::Sleep(1000);
           AfxMessageBox("Just executed App.Quit()");
    
          }  // End of processing logic.
    
          catch(COleException *e)
          {
            char buf[1024];
    
            sprintf(buf, "COleException. SCODE: %08lx.", (long)e->m_sc);
            ::MessageBox(NULL, buf, "COleException", MB_SETFOREGROUND | MB_OK);
          }
    
          catch(COleDispatchException *e)
          {
           char buf[1024];
           sprintf(buf,
                   "COleDispatchException. SCODE: %08lx, Description: \"%s\".",
                   (long)e->m_wCode,
                   (LPSTR)e->m_strDescription.GetBuffer(1024));
           ::MessageBox(NULL, buf, "COleDispatchException",
                        MB_SETFOREGROUND | MB_OK);
          }
    
          catch(...)
          {
           ::MessageBox(NULL, "General Exception caught.", "Catch-All",
                        MB_SETFOREGROUND | MB_OK);
          }
    					
  5. 您可能需要修改程式碼中 CAutoProjectDlg::OnRun() 以指出您的活頁簿 Test.xls 正確的路徑。在下面這一行中參考活頁簿:
          lpDisp = books.open("C:\\Test", . . .);
    					

?考

取得更多資訊有關自動化 Office 應用程式按一下面的文件編號,檢視 「 Microsoft 知識庫 」 中的發行項:
222101如何尋找並使用 Office 物件模型文件

屬性

文章編號: 178783 - 上次校閱: 2007年1月22日 - 版次: 4.1
這篇文章中的資訊適用於:
  • Microsoft Foundation Class Library 4.2?應用於:
    • Microsoft Visual C++ 5.0 Standard Edition
    • Microsoft Visual C++ 6.0 Service Pack 5
    • Microsoft Excel 97 Standard Edition
  • Microsoft Office XP Developer Edition
  • Microsoft Office 2000 Developer Edition
  • Microsoft Excel 2002 Standard Edition
關鍵字:?
kbmt kbautomation kbhowto kbinterop KB178783 KbMtzh
機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:178783
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com