MFC import and export to EXCEL

https://wenku.baidu.com/view/d7383548767f5acfa1c7cd30.html

Just look at this

copy version

The operation of VC2010 to Excel

  1. Create a new C++ project

Create a dialog-based MFC program

  1. Add library, add Excel class library

Right-click on the project name, select "Add" - "Class" (or click "Project" -> "Add Class" in the menu bar), and select "MFC Class From TypeLib" (MFC Class From TypeLib)

 

Select "Registry" for the class source, select "Microsoft Excel 11.0 Object Library<1.5>" in the available type libraries, and select the required class in the interface list box. Here, we select _Application, _Workbook, Worksheet, Range, Workbooks , Worksheets these six on it.

 

As you can see, six classes have been added.

  1. Modify header files

Comment out "#import "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE" no_namespace" above the six header files added.

  1. add header file

Add these header files to the stdAfx.h header file

#include "CApplication.h"

#include "CRange.h"

#include "CWorkbook.h"

#include "CWorkbooks.h"

#include "CWorksheet.h"

#include "CWorksheets.h"

  1. correct mistakes

Compile, there will be two errors:

…\crange.h(335): warning C4003: Insufficient arguments for 'DialogBoxW' macro

…\crange.h(335): error C2059: syntax error: ","

Double-click the error message to locate the error line,

    VARIANT DialogBox()

    {

         VARIANT result;

         InvokeHelper(0xf5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);

         return result;

    }

Add "_" underscore before the function name "DialogBox()", that is, "_DialogBox()", so that the compilation is successful.

  1. Add an edit box in the dialog box and associate it with a CEdit type variable m_Path, and add an "Open" button to open an existing Excel file. and display the path in the edit box. The implementation code is as follows.

void CExportToExcelDlg::OnBnClickedButtonOpen()

{

  CFileDialog file(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,

       _T("EXCEL文件t(*.xls;*.xlsx)|*.xls;*.xlsx||"),AfxGetMainWnd());

  if(file.DoModal()==IDOK)

  {

       CString strPath=file.GetPathName();

       m_Path.SetWindowTextW(strPath);

       CApplication app;

       CWorkbook book;

       CWorkbooks books;

       if (!app.CreateDispatch(_T("Excel.Application")))

       {

           MessageBox(_T("Error!Creat Excel Application Server Faile!"));

           exit(1);

       }

       //books.AttachDispatch(app.get_Workbooks(),true);

       //book.AttachDispatch(books.Add(_variant_t(strPath)));

       books = app.get_Workbooks();      

       book = books.Add(_variant_t(strPath));

 

       app.put_Visible(true);

 

       //end, release

       book.ReleaseDispatch();  

       books.ReleaseDispatch();  

       app.ReleaseDispatch();

       app.Quit();

 

  }

}

 

  1. Add a "Write" button in the dialog box to create a new Excel file (overwrite if it exists), and write data to the file. The implementation code is as follows.

void CExportToExcelDlg::OnBnClickedButtonWrite()

{

  CString strFile = _T("D:\\WriteToExcelTest.xlsx");

 

  COleVariant

       covTrue((short)TRUE),

       covFalse((short)FALSE),

       covOptional((long)DISP_E_PARAMNOTFOUND,   VT_ERROR);

 

  CApplication app;

  CWorkbook book;

  CWorkbooks books;

  CWorksheet sheet;

  CWorksheets sheets;

  CRange range;

  CFont font;

 

  if (!app.CreateDispatch(_T("Excel.Application")))

  {

       MessageBox(_T("Error!Creat Excel Application Server Faile!"));

  }

 

  books = app.get_Workbooks();

  //books.AttachDispatch(app.get_Workbooks()); can replace the above line

  book = books.Add(covOptional);

  //book.AttachDispatch(books.Add(covOptional),true); can replace the above line

  sheets=book.get_Worksheets();

  //sheets.AttachDispatch(book.get_Worksheets(),true); can replace the above line

  sheet = sheets.get_Item(COleVariant((short)1));

  //sheet.AttachDispatch(sheets.get_Item(_variant_t("sheet1")),true); can replace the above line

  //The following two lines are to write "Yeah! I can write data to excel!" to A1

  range = sheet.get_Range(COleVariant(_T("A1")),COleVariant(_T("A1")));

  range.put_Value2(COleVariant(_T("Yeah!I can write data to excel!")));

 

  //The following is to enter 1 to 10, ten numbers into the first ten cells of the second row

  for(long i=1;i<11;i++)

       range.put_Item(_variant_t((long)2),_variant_t((long)i),_variant_t((long)i));

 

  //set column width

  range = sheet.get_Range(COleVariant(_T("A1")),COleVariant(_T("J1")));

  range.put_ColumnWidth(_variant_t((long)5));

 

  // display the table

  app.put_Visible(TRUE);

 

  //keep

  book.SaveCopyAs(COleVariant(strFile));

  book.put_Saved(true);

 

  //end, release

  book.ReleaseDispatch();  

  books.ReleaseDispatch();  

  app.ReleaseDispatch();

  app.Quit();

 

}

 

  1. Add a list control in the dialog box, associate the variable m_Grid, and set the display style as a report. Add the "Write List" button in the dialog box to write the existing table in the dialog box to Excel. The implementation code is as follows.

In the initialization function, the list is initialized first.

//Set the extension style of the list view

    m_Grid.SetExtendedStyle(LVS_EX_FLATSB //Display scroll bar in flat style

         |LVS_EX_FULLROWSELECT //Allow the entire row to be selected

         |LVS_EX_HEADERDRAGDROP //Allow entire column to drag

         |LVS_EX_ONECLICKACTIVATE //Click the selected item

         |LVS_EX_GRIDLINES); //Draw grid lines

    //set the header

    m_Grid.InsertColumn(0,_T("编号"),LVCFMT_LEFT,100,0);

    m_Grid.InsertColumn(1,_T("姓名"),LVCFMT_LEFT,100,1);

    m_Grid.InsertColumn(2,_T("Department"),LVCFMT_LEFT,100,2);

    //insert data into the list

    int count = 0;

    m_Grid.InsertItem(count,_T("001"));

    m_Grid.SetItemText(count,1,_T("张一"));

    m_Grid.SetItemText(count++,2,_T("Sales"));

    m_Grid.InsertItem(count,_T("002"));

    m_Grid.SetItemText(count,1,_T("列二"));

    m_Grid.SetItemText(count++,2,_T("R&D Department"));

    m_Grid.InsertItem(count,_T("003"));

    m_Grid.SetItemText(count,1,_T("宇三"));

    m_Grid.SetItemText(count++,2,_T("Purchasing Department"));

    m_Grid.InsertItem(count,_T("004"));

    m_Grid.SetItemText(count,1,_T("宙四"));

    m_Grid.SetItemText(count,2,_T("Propaganda Department"));

 

Rewrite the response function of the button

void CExportToExcelDlg::OnBnClickedButtonWritelist()

{

         // TODO: Add control notification handler code here

         CString strFile = _T("D:\\WriteListToExcelTest.xlsx");

 

         COleVariant

                  covTrue((short)TRUE),

                  covFalse((short)FALSE),

                  covOptional((long)DISP_E_PARAMNOTFOUND,   VT_ERROR);

 

         CApplication app;

         CWorkbook book;

         CWorkbooks books;

         CWorksheet sheet;

         CWorksheets sheets;

         CRange range;

 

         if (!app.CreateDispatch(_T("Excel.Application")))

         {

                  MessageBox(_T("Error!Creat Excel Application Server Faile!"));

                  exit(1);

         }

         books = app.get_Workbooks();

         book = books.Add(covOptional);

         sheets = book.get_Worksheets();

         sheet = sheets.get_Item(COleVariant((short)1));

         //Get all Cells

         range.AttachDispatch(sheet.get_Cells());

         CString sText[]={_T("Number"),_T("Name"),_T("Department")};

         for (int setnum = 0; setnum <m_Grid.GetItemCount () + 1; setnum ++)

         {

                  for (int num=0; num<3; num++)

                  {

                          if (! setnum)

                          {

                                   range.put_Item(_variant_t((long)(setnum+1)),_variant_t((long)(num+1)),

                                            _variant_t(sText[num]));

                          }

                          else

                          {

                                   range.put_Item(_variant_t((long)(setnum+1)),_variant_t((long)(num+1)),

                                            _variant_t (m_Grid.GetItemText (setnum-1, num)));

                          }

                  }

         }

         //keep

         book.SaveCopyAs(COleVariant(strFile));

         book.put_Saved(true);

         app.put_Visible(true);

        

         // release the object

         range.ReleaseDispatch();

         sheet.ReleaseDispatch();

         sheets.ReleaseDispatch();

         book.ReleaseDispatch();

         books.ReleaseDispatch();

         app.ReleaseDispatch();

         app.Quit();

 

}

The final result is as follows.

 

Press the [Open] button, the Open dialog box will appear, and you can select Excel to open.

 

Press the [Write] button to open the Excel file.

 

Press [Write List] to open the Excel file.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324981465&siteId=291194637