1. 程式人生 > >MFC對匯出Excel的詳細講解

MFC對匯出Excel的詳細講解

MFC讀寫Excel詳細步驟

說明 : 程式碼編譯可能會編譯不通過,主要是看註釋說明.

準備工作:
開啟開發環境VC或VS新建一個基於對話方塊的簡單工程; 通過類嚮導新增類-->型別庫中的MFC類

開啟建立類對話方塊

       選擇檔案,位置編輯框填入Excel.exe的詳細目錄,可以通過瀏覽選擇,在介面下方選擇_Application(應用),_Workbook(視窗)Workbooks(整個視窗),Worksheets(單個表單),Worksheets(整個表單),Range(元素集合)六個基本的介面並生成類。選擇介面後單擊向右的單箭頭即可,雙箭頭是生成所有介面的類;

       生成類之後將新增的幾個類的標頭檔案中的#import "E:\\Microsoft Office\\Office14\\EXCEL.EXE" no_namespace 註釋掉,加上#include<afxdisp.h>。然後編譯,出現下面這倆個錯誤;點選DialodBoxA找到錯誤位置將DialodBox改為_DialodBox;再編譯,沒有錯誤;warning C4003: “DialogBoxA”巨集的實參不足 error C2059: 語法錯誤:“,” 在要操作Excel類的CPP檔案中包含標頭檔案:

準備工作完成。

向Excel寫資料:

CFileDialogdlg(FALSE, ".xlsx",NULL,
            OFN_FILEMUSTEXIST|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
            "Microsoft ExcelFiles(*.xls)|*.xls|Microsoft Excel Files(*.xlsx)(推薦)|*.xlsx|All Files (*.*)|*.*||");
    Files(*.xls)|*.xls|Microsoft Excel Files(*.xlsx)(推薦)|*.xlsx|All Files (*.*)|*.*||");
    dlg.m_ofn.lpstrTitle =	" 儲存到 Excel" ;
    if(dlg.DoModal() ==	IDOK)
    {
    // 獲取路徑
    CString strFileName=dlg.GetPathName(); CWorkbooks	books;
    CWorkbook book; 
    CApplication app; 
    CWorksheets	sheets;
    CWorksheet sheet;
    CRange range;
    CMyFont	font;
    CRange cols;
    COleVariant covOptional(( long ) DISP_E_PARAMNOTFO,UVNTD_ERROR); 
    if(!app.CreateDispatch("Excel.Application"))
    {
        this -> MessageBox("無法建立 Excel 應用!"); 
        return;
    }
    books=app.get_Workbooks();
    book=books.Add(covOptional); 
    sheets=book.get_Worksheets(); 
    sheet=sheets.get_Item(COleVariant((short)1));
    //獲得(A,1)(B,1) 兩個單元格
    range=sheet.get_Range(COleVariant("A1"),COleVariant("B6"));
    //設定公式“=RAND()*100000”
    range.put_Formula(COleVariant("=RAND()*1000"));
    //選擇整列,並設定寬度為自適應
    cols = range.get_EntireColumn(); 
    cols.AutoFit();
    //設定字型為粗體
    font = range.get_Font();
    font.put_Bold(COleVariant((short)TRUE));
    //設定數字格式為貨幣型
    //range.put_NumberFormat(COleVariant("$0.00"));
    CString	Range327[]={"C1","C2","C3","C4","C5","C6"};
    CString fileinfo[]={"齒形","齒向","齒距","左齒面","右齒面","徑跳"}; 
    for(int	i=0;i<6;i++)
    {
        range = sheet.get_Range(COleVariant(Range327[i]),COleVariant(Range327[i]));
        range.put_Value2(COleVariant (fileinfo[i]));
    }
    /*
    //獲得座標為(C,2)單元格   
    //顯示Excel 表
    range = sheet.get_Range(COleVariant("C1"), COleVariant("F10"));
    //設定單元格內容位 Hello Excel
    range.put_Value2(COleVariant("哈爾濱精達測量儀器有限公司"));
    */
    //選擇整列,並設定寬度為自適應
    cols = range.get_EntireColumn(); 
    cols.AutoFit();

     //顯示列表控制元件
 
    //app.put_Visible(TRUE);
    //允許其他使用者控制 Excel ,否則 Excel 、將一閃而過
    //app.put_UserControl(TRUE);
 
    book.SaveCopyAs( COleVariant (strFileName)); 
    book.put_Saved( true );

    range.ReleaseDispatch(); 
    font.ReleaseDispatch(); 
    cols.ReleaseDispatch(); 
    sheet.ReleaseDispatch(); 
    sheets.ReleaseDispatch(); 
    book.ReleaseDispatch(); 
    books.ReleaseDispatch();
    //以下關閉應用的兩條程式碼結合使用且順序不能反,否則無法關閉程序
    app.Quit(); 
    app.ReleaseDispatch();
    }

    讀取Excel中的資料:
    UpdateData(TRUE); 
    str327=""; 
    UpdateData(FALSE); 
    CApplication app; 
    CWorkbooks books; 
    CWorkbook book; 
    CWorksheets sheets; 
    CWorksheet sheet; 
    CRange range; 
    CRange oCurCell;
    CString	strFileName1;
    CFileDialog	dlg(TRUE,".xlsx",NULL,
                    OFN_FILEMUSTEXIS| OT FN_HIDEREADON| OLYFN_OVERWRITEPRO, 
                    M"MPiTcrosoft ExcelFiles(*.xls)|*.xls|Microsoft Excel Files(*.xlsx)|*.xlsx|All Files(*.*)|*.*||");
    dlg.m_ofn.lpstrTitle ="開啟Excel檔案";
    int nRetVal = dlg.DoModal(); 
    if(nRetVal == IDOK)
    {
        if(!app.CreateDispatch(_T("Excel.Application"),NULL))
        {
            ::MessageBox(NULL,_T("建立Excel 服務失敗"),_T("錯誤提示"),MB_OK|MB_ICONERROR); 
            return;
            //exit(1);
        }
        // 設定為顯示
        app.put_Visible(FALSE); 
        books.AttachDispatch(app.get_Workbooks(),TRUE); 
        LPDISPATClHpDisp = NULL;
        COleVariant covTrue((short)TRUE);
        COleVariant covFalse((short)FALSE);
        COleVariant covOptional((long)DISP_E_PARAMNOTFO,UNVDT_ERROR);

        //開啟檔案
        CString strFilePath=dlg.GetPathName(); 
        strFileName1=strFilePath;
        //研發人員名單  2016.xls";
        lpDisp = books.Open( strFilePath,
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
 
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing),
        _variant_t	(vtMissing) );

        //獲得活動的WorkBook(工作簿) 
        book.AttachDispatch(lpDisp,	TRUE);
        //獲得活動的WorkSheet(工作表) 
        sheet.AttachDispatch(book.get_ActiveSheet(),TRUE);
        //獲得使用的區域 Range(區域) 
        range.AttachDispatch(sheet.get_UsedRange(),TRUE);

        //獲得使用的行數
        long lgUsedRowNum = 0; 
        range.AttachDispatch(range.get_Rows(),TRUE); 
        lgUsedRowNum = range.get_Count();
        //獲得使用的列數
        long lgUsedColumnNum = 0; 
        range.AttachDispatch(range.get_Columns(),TRUE); 
        lgUsedColumnNum = range.get_Count();
        //讀取Sheet的名稱
        CString strSheetName = sheet.get_Name();

        //得到全部Cells ,此時,CurrRange 是cells	的集合
        range.AttachDispatch(sheet.get_Cells(),	TRUE);
        //遍歷整個Excel 表格
        CStringArray* arrayStr;
        arrayStr =newCStringArray [lgUsedRowNum]; 
        for (int i = 0; i <lgUsedRowNum; )	// 遍歷行
        {
            for(int	j = 1; j <= lgUsedColumnNum; )	// 遍歷列
            {
                    oCurCell.AttachDispatch(range.get_Item(COleVariant((long)(i+ 1)),COleVariant((long)j)).pdispVal,TRUE);
                    VARIANTvarItemName = oCurCell.get_Text();
                    CString strItemName;
                    strItemName = varItemName.bstrVal;
                    //AfxMessageBox(strItemName );
                    //判斷是否是合併的單元格
                    VARIANTvarMerge = oCurCell.get_MergeCells(); CString
                    PosInfo1[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T"};
                    CString PosInfo2[]={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"};
                    if(varMerge.boolVal == -1 )
                    {
                        AfxMessageBox( PosInfo1[j-1]+PosInfo2[i]+"是合併的單元格!");
                    }
                    //else if ( varMerge.boolVal == 0 )
                    //{
                    //AfxMessageBox( _T( "	不是合併的單元格 !" ) );
                    //}
         } i++;
}
 
        arrayStr[i].Add( strItemName ); 
        j++;

        if(lgUsedColumnNum*lgUsedRowNum>=300)
        {
            MessageBox( " 檔案過大,儲存空間不足,無法讀取!	" ); goto LLL;
        }

        CString strTempValue[20][20];
        for(int	i = 0; i <lgUsedColumnNum; i++)	// 遍歷列
        {
            for(int	j = 0; j <lgUsedRowNum; j++)// 遍歷行
            {
                  strTempValue[i][j]=arrayStr[j].GetAt(i);
            }
        }
        //釋放二維陣列
        delete [] arrayStr;

        //這裡設定了字串型別,應該還能設定其它型別引數,比如說整型。解開上面程式碼中的註釋,
        可以嘗試下其它功能。參考資源	[1]
        // 釋放資源
        //	book.SaveCopyAs(COleVariant(strFilePath));
        //	book.put_Saved(true); 
        book.ReleaseDispatch();
        books.ReleaseDispatch(); 
        app.Quit(); 
        app.ReleaseDispatch();
        long size327=lgUsedColumnNum*lgUsedRowNum;
        datafloat=atof(strTempValue[0][0]); UpdateData( TRUE);
        for (int i = 0; i <lgUsedColumnNum; i++)// 遍歷列
        {
            if(i!=0)
            {
                str327=str327+"\r\n";
            }
            for	( int	j = 0; j <lgUsedRowNum; j++)
            {
                if	(!strTempValue[i][j].IsEmpty())
                {
                    str327=str327+	"\r\n"	+strTempValue[i][j];
                }
            }
        }
            m_ddd=datafloat; 
            UpdateData(FALSE);
        }
        //book.SaveCopyAs(COleVariant(strFileName1));
        //book.put_Saved(true);
        // 不顯示任何警告對話方塊
        // 在儲存檔案程式碼之前加上下面兩句語句
        app.put_AlertBeforeOverwriting(	false );
        app.put_DisplayAlerts(false );
        // 將對應 Excel 程序關閉
        range.ReleaseDispatch(); 
        oCurCell.ReleaseDispatch(); 
        sheet.ReleaseDispatch(); 
        sheets.ReleaseDispatch(); 
        book.ReleaseDispatch();
        books.ReleaseDispatch();
        // 以下關閉應用的兩條程式碼結合使用且順序不能反,否則無法關閉程序
        app.Quit();
        app.ReleaseDispatch();
        }
    }
}

轉載自 : 百度文庫

 

下面也有相應的詳細文章:

第一篇 : https://www.cnblogs.com/tianya2543/p/4165997.html

第二篇 : https://blog.csdn.net/qivan/article/details/7599924