MFC read-in Export to Excel

Source: Internet
Author: User

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

That's all I'm looking for.

Copy version

VC2010 Operations on Excel

    1. Create a new C + + project

To create a dialog-based MFC program

    1. Add a library, add an Excel class Library

Right-click on the project name, select "Add"-"class" (or by clicking on "Project", "Add Class" in the menu bar) and select "MFC Class in TypeLib" (MFC classes from TYPELIB)

Class Source Select "Registry", in the Available type library choose "Microsoft Excel 11.0 Object library<1.5>" In the Interface list box select the desired class, where we select _application,_workbook, Worksheet,range,workbooks,worksheets the six of them.

As you can see, six classes have been added in.

    1. modifying header files

The "#import" above the six header files will be added separately C:\\Program Files\\Microsoft Office\\office11\\excel. EXE "No_namespace" commented out.

    1. Add header File

Add these header files in the StdAfx.h header file

#include "CApplication.h"

#include "CRange.h"

#include "CWorkbook.h"

#include "CWorkbooks.h"

#include "CWorksheet.h"

#include "CWorksheets.h"

    1. Modify Error

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 prompt, locate the error line,

VARIANT DialogBox ()

{

VARIANT result;

InvokeHelper (0xf5, Dispatch_method, Vt_variant, (void*) &result, NULL);

return result;

}

The function name "DialogBox ()" is preceded by an "_" underscore, which is "_dialogbox ()" so that it can be compiled successfully.

    1. Add an edit box to 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 displays 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 file 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 to the dialog box to create a new Excel file (overwrite 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 line above

Sheets=book.get_worksheets ();

Sheets. AttachDispatch (Book.get_worksheets (), true); Can replace the line above

Sheet = Sheets.get_item (COleVariant ((short) 1));

Sheet. AttachDispatch (Sheets.get_item (_variant_t ("Sheet1"), true); Can replace the line above

The following two lines are written to A1 "yeah! I can write data to excel! "

Range = Sheet.get_range (COleVariant (_t ("A1")), COleVariant (_t ("A1"));

Range.put_value2 (COleVariant (_t ("yeah! I can write data to excel! ")));

Here are 1 to 10, 10 digits to the first 10 cells in 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 widths

Range = Sheet.get_range (COleVariant (_t ("A1")), COleVariant (_t ("J1"));

Range.put_columnwidth (_variant_t ((long) 5));

Show Table

App.put_visible (TRUE);

Save

Book. SaveCopyAs (COleVariant (strfile));

Book.put_saved (TRUE);

End, release

Book. ReleaseDispatch ();

Books. ReleaseDispatch ();

App. ReleaseDispatch ();

App. Quit ();

}

    1. Adds a list control to the dialog box, associates the variable M_grid, and sets the display as a report style. Add the Write List button to the dialog box to write the tables already in the dialog box to Excel. The implementation code is as follows.

In the initialization function, the list is initialized first.

Set the extended style of the list view

M_grid.setextendedstyle (LVS_EX_FLATSB//flat style display scroll bar

| Lvs_ex_fullrowselect//Allow entire row to be selected

| Lvs_ex_headerdragdrop//Allow entire column to be dragged

| Lvs_ex_oneclickactivate//Click the selected item

|                                  Lvs_ex_gridlines); Draw a grid line

Set up the table header

M_grid.insertcolumn (0,_t ("number"), lvcfmt_left,100,0);

M_grid.insertcolumn (1,_t ("name"), lvcfmt_left,100,1);

M_grid.insertcolumn (2,_t ("department"), lvcfmt_left,100,2);

Inserting data into the list

int count = 0;

M_grid.insertitem (count,_t ("001"));

M_grid.setitemtext (count,1,_t ("Zhang Yi"));

M_grid.setitemtext (count++,2,_t ("Sales Department"));

M_grid.insertitem (count,_t ("002"));

M_grid.setitemtext (count,1,_t ("column Two"));

M_grid.setitemtext (count++,2,_t ("Research and Development Department"));

M_grid.insertitem (count,_t ("003"));

M_grid.setitemtext (count,1,_t ("Yu San"));

M_grid.setitemtext (count++,2,_t ("purchasing department"));

M_grid.insertitem (count,_t ("004"));

M_grid.setitemtext (count,1,_t ("Joe IV"));

M_grid.setitemtext (count,2,_t ("propaganda Department"));

Then write 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 ("affiliated 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)));

}

}

}

Save

Book. SaveCopyAs (COleVariant (strfile));

Book.put_saved (TRUE);

App.put_visible (TRUE);

Releasing objects

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 appears, you can select Excel to open.

Press the Write button to open the Excel file.

Press "Write list" to open the Excel file.

MFC read-in Export to Excel

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.