我的電腦上,office版本是2007的,安在C盤的默認(rèn)位置上。
生成時(shí),選擇“單文檔框架”,“Compound document support: Container ”其他默認(rèn)~
在“ClassView”視圖中,右鍵單擊project,添加class。
選擇“MFC->MFC Class from TypeLib”
Add class from:Registry中,選擇“Microsoft Excel 12.0 Object Library<1.6>”
在下面選擇,“_Application, _Worksheet, _Workbook, Font, Range, Worksheets, Workbooks”到右側(cè)的“Generated classes”并單擊確定。
把生成的CRange.h和CRange0.h中的“DialogBox”函數(shù)前面加上一個(gè)下劃線,改成“_DialogBox”
注銷掉,所有新添加的類的頭文件中的“//#import "C:\\Program Files\\Microsoft Office\\Office12\\EXCEL.EXE" no_namespace” 語句。
并把這些頭文件中都添加一下代碼
#include
#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE12\\mso.dll" rename("RGB", "MSRGB") rename("DocumentProperties", "JOEDocumentProperties")
#import "C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB" raw_interfaces_only, rename("Reference", "ignorethis"), rename("VBE", "JOEVBE")
#import "C:\\Program Files\\Microsoft Office\\OFFICE12\\excel.exe" exclude("IFont", "IPicture") rename("RGB", "ignorethis"), rename("DialogBox", "ignorethis"), rename("VBE", "JOEVBE"), rename("ReplaceText", "JOEReplaceText"), rename("CopyFile","JOECopyFile"), rename("FindText", "JOEFindText"), rename("NoPrompt", "JOENoPrompt")
using namespace Office;
using namespace VBIDE;
using namespace Excel ;
在這些新添加的頭文件的起始處添加:
#ifndef _XXXX_H
#define _XXXX_H
其中XXXX為文件名或者自行定義本頭文件專用的宏標(biāo)記
頭文件尾部添加:
#endif
stdafx.h中include這些都文件~
于是就可以使用excel的編程方法咯。
比如,新建一個(gè)菜單欄選項(xiàng),并添加消息響應(yīng)函數(shù),在其中添加如下代碼:
CApplication app;
CWorkbooks books;
CWorkbook book;
CWorksheets sheets;
CWorksheet sheet;
CRange0 range;
CFont0 font;
CRange0 cols;
int i = 3;
CString str1, str2;
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if( !app.CreateDispatch(_T("Excel.Application")))
{
MessageBoxW(_T("無法創(chuàng)建Excel應(yīng)用!"));
return;
}
books=app.get_Workbooks();
book=books.Add(covOptional);
sheets=book.get_Sheets();
sheet=sheets.get_Item(COleVariant((short)1));
range=sheet.get_Range(COleVariant(_T("A1")),COleVariant(_T("A1")));
range.put_Value2(COleVariant(_T("HELLO EXCEL!")));
font=range.get_Font();
font.put_Bold(COleVariant((short)TRUE));
range=sheet.get_Range(COleVariant(_T("A2")),COleVariant(_T("A2")));
range.put_Formula(COleVariant(_T("=RAND()*")));
range.put_NumberFormat(COleVariant(_T("$0.00")));
str1.Format(_T("A%d"),i);
str2.Format(_T("A%d"),i);
range=sheet.get_Range(COleVariant(str1),COleVariant(str2));
str1.Format(_T("%d"),44);
range.put_Value2(COleVariant(str1));
cols=range.get_EntireColumn();
cols.AutoFit();
app.put_Visible(TRUE);
app.put_UserControl(TRUE);
經(jīng)測試,可以運(yùn)行~