vs2010操做 office2010自我筆記

【FAG按順序添加這些東西】
1.建立一個新的工程,選擇mfc application,選擇dialog,在advanced features選擇automation(這一項我不肯定有沒有必要,查資料說要選上,我就選上了)
2.建立完工程後,在dialog對話框上右擊,選擇class wizard(或是ctrl+shift+x)
3.在add class下拉框內選擇add class from typelib
4.在add class from下面選擇file,而後你的office安裝目錄下的EXCEL.EXE(個人目錄是C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE)
5.在下面添加6個類到咱們的工程,(_Application, Worksheets, _Worksheet, Workbooks, _Workbook, Range)注意有的有下劃線,別添加錯了git

【FAG註釋掉下面】
把導入的6個類對應的頭文件最開始的一句話[註釋]markdown

#import "C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE" no_namespace

【FAG添加下劃線】
把Range這個類自動生成的頭文件(我這是CRage.h)裏面的
VARIANT DialogBox()
VARIANT _DialogBox() app

【FAG添加頭文件】函數

//====6個類的頭文件================================
#include "CApplication.h"  
#include "CRange.h"  
#include "CWorkbook.h"  
#include "CWorkbooks.h"  
#include "CWorksheet.h"  
#include "CWorksheets.h" 

//====裏面定義變量時用到==============================
#include <map>
#include <utility>
using namespace std;

【FAG使用函數】ui

void Cfag_EXCEL00Dlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    ::CoInitialize(NULL);
    //用到六個excel類
    //要操做表,必須先逐步獲取Workbooks->Workbook->Worksheets->Worksheet->Range
    CApplication app;   //先建立一個_Application類,用_Application來建立一個Excel應用程序接口
    CWorkbooks books;   //工做薄集合
    CWorkbook book;     //工做薄
    CWorksheets sheets; //工做表集合
    CWorksheet sheet;   //工做表
    CRange range;       //單元格區域對象

    //star excel
    if (!app.CreateDispatch("Excel.Application"))
    {
        AfxMessageBox("沒法啓動Excel啓動器");
        return ;
    }

    //=======================

    //========================
    //open *.xls
    books.AttachDispatch(app.get_Workbooks());
        //get file path
    LPCTSTR szFilter = _T("txt(*.txt)|*.txt|excel(*.xls)|*.xls|All Filter(*.*)|*.*||");
    CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY,szFilter);
    if (IDOK != dlg.DoModal())
    {
        return ;
    }
    //獲得excel的路徑
    CString strPath = dlg.GetPathName();

     /* COleVariant類爲VARIANT數據類型的包裝, 在自動化程序中,一般都使用ARIANT數據類型進行參數傳遞。 故下列程序中,函數參數都是經過COleVariant類來轉換了的。 */  

    //covOptional 可選參數的VARIANT類型
    COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

    //打開books
    LPDISPATCH lpDisp = books.Open(strPath,covOptional,covOptional,covOptional,
                                    covOptional,covOptional,covOptional,covOptional,
                                    covOptional,covOptional,covOptional,covOptional,
                                    covOptional,covOptional,covOptional);
    //get workbook【獲得book】
    book.AttachDispatch(lpDisp);

    //get worksheets【獲得sheets】
    sheets.AttachDispatch(book.get_Worksheets());

    //get the current active sheet【獲得sheet】
    lpDisp = book.get_ActiveSheet();
    sheet.AttachDispatch(lpDisp);

    //get used regional information【獲得已經使用區域的原始信息】
    CRange UsedRange;
    UsedRange.AttachDispatch(sheet.get_UsedRange());

    //get used line numbers【獲得已經使用行的數目】
    range.AttachDispatch(UsedRange.get_Rows());
    long iRowNum = range.get_Count();

    //get used column numbers【獲得已經使用列的數目】
    range.AttachDispatch(UsedRange.get_Columns());
    long iColNum = range.get_Count();

    //read the starting line and column【讀取行和列的開始信息】
    long iStarRow = UsedRange.get_Row();
    long iStarCol = UsedRange.get_Column();

    //read the table values【讀取每一個單元格的數值】


    for (;iStarRow <= iRowNum;iStarRow++)//控制行循環
    {
        for (iStarCol = UsedRange.get_Column();iStarCol <= iColNum;iStarCol++)//控制列循環
        {   
            //獲得sheet中全部單元格,並放入range中
            range.AttachDispatch(sheet.get_Cells());

            //從已經被使用的單元中,選出一個,並放入range中
            range.AttachDispatch(range.get_Item(COleVariant(iStarRow),COleVariant(iStarCol)).pdispVal);

            //取出單元格數據放入vResult結構體中
            COleVariant vResult = range.get_Value2();

           //將vResult結構體變量解析成爲CString類型,放入str中。
            CString str;
            if (vResult.vt == VT_BSTR)//character string【若是是中文】
            {
                str = vResult.bstrVal;
            }
            else if (vResult.vt == VT_R8)//8 byte of digital【或是數字】
            {
                str.Format("%f",vResult.dblVal);
            }
            else if (vResult.vt == VT_DATE)//date time【時間】
            {
                SYSTEMTIME st;
                VariantTimeToSystemTime(vResult.date,&st);
            }
            else if (vResult.vt == VT_EMPTY)//blank space【空白區】
            {
                str = "";
            }


            strResultNum.first = iStarRow; //單元格行標
            strResultNum.second = iStarCol;//單元格列標

            strResult[strResultNum] = str;//此位置單元格的字符串
        }
    }

    //release
    sheet.ReleaseDispatch();//釋放sheet
    sheets.ReleaseDispatch();//釋放sheets
    book.Close(covOptional,COleVariant(strPath),covOptional);//關閉book
    books.Close();//關閉books
    app.Quit();//關閉app
    //CoUninitialize();


}


void Cfag_EXCEL00Dlg::OnBnClickedButton2()
{
    // TODO: Add your control notification handler code here
    ::CoInitialize(NULL);
    //export to excel

    //get the export file path
    CFileDialog dlg(FALSE,NULL,NULL,OFN_HIDEREADONLY,"excel(*.xls)|*.xls|txt(*.txt)|*.txt|All Filter(*.*)|*.*||");
    if (IDOK != dlg.DoModal())
    {
        return ;
    }
    CString fname = dlg.GetPathName();

    //define the objects
    CApplication objApp;
    CWorkbooks objBooks;
    CWorkbook objBook;
    CWorksheets objSheets;
    CWorksheet objSheet;
    CRange objRange;

    COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR),
                covTrue(    (short)TRUE     ),
                covFalse(   (short)FALSE    ),
                varFormat(  (short)-4143    ),
                varCenter(  (short)-4108    ),
                varLeft(    (short)-4131    ),
                varText(    "TEXT",VT_BSTR  );

    //creat excel
    objApp.m_bAutoRelease = TRUE;
    if (!objApp.CreateDispatch("Excel.Application"))
    {
        AfxMessageBox("Failed to connect to excel!");
        return ;
    }

    //get Workbooks
    objBooks = objApp.get_Workbooks();

    //open excel file
    objBook.AttachDispatch(objBooks.Add(_variant_t("")));

    //get worksheets
    objSheets = objBook.get_Worksheets();

    //get worksheet【獲取第一個工做表】
    objSheet = objSheets.get_Item((_variant_t)short(1));

    //set worksheet name
    CString sheetname = "答案設置";
    objSheet.put_Name(sheetname);

    //write to cells
    CString s1;
    CString s;
    pair<long,long> sNum;
    CRange objRange1;
    int row,col;
    CString strRow;
    CString strName = fname;
    char cCell;
    for (row = 1;row <= strResultNum.first;row++)
    {
        for (col = 1;col <= strResultNum.second;col++)
        {
            //get the unit head
            cCell = 'A' + col - 1;//A
            strName.Format(_T("%c"),cCell);//A
            strRow.Format(_T("%d"),row);//1
            strName += strRow;//strName=A1

            s1.Format(strName);
            objRange1 = objSheet.get_Range(_variant_t(s1),_variant_t(s1));//移到A1這個單元格

            //get the unit value【往此格里裝值】
            sNum.first = row;
            sNum.second = col;
            s = strResult[sNum];
            objRange1.put_FormulaR1C1(_variant_t(s));
            //【put_FormulaR1C1】返回或設置指定對象的公式
        }
    }

    //save【保存一些後續的工做就行】
    objBook.SaveAs(     _variant_t(fname),
                        varFormat,
                        covOptional,
                        covOptional,
                        covOptional,
                        covOptional,
                        0,
                        covOptional,
                        covOptional,
                        covOptional,
                        covOptional,
                        covOptional
                    );

    //release
    objApp.Quit();
    objRange.ReleaseDispatch();
    objSheet.ReleaseDispatch();
    objSheets.ReleaseDispatch();
    objBook.ReleaseDispatch();
    objBooks.ReleaseDispatch();
}
相關文章
相關標籤/搜索