zoukankan      html  css  js  c++  java
  • VC2010对Excel的操作

    1.创建新的C++工程


    创建基于对话框的MFC程序


    2.添加库、添加Excel类库


    在工程名上右键,选择“添加”—“类”(或者点击菜单栏的“项目”->“添加类”),选择“TypeLib中的MFC类”(MFC Class From TypeLib)



    类来源选“注册表”,在可用的类型库中选择“MicrosoftExcel 14.0 Object Library<1.7>”在接口列表框中选择需要的类,在此,我们选择_Application,_Workbook,Worksheet,Range,Workbooks,Worksheets这六个就可以了。




     

    可以看到,六个类被添加了进来。


    3.修改头文件


    分别将加进来的六个头文件上面的“#import "C:\ProgramFiles\Microsoft Office\OFFICE11\EXCEL.EXE" no_namespace”注释掉。



     

    4.添加头文件

    在stdAfx.h头文件中添加加进来的这几个头文件

    #include "CApplication.h"
    #include "CRange.h"
    #include "CWorkbook.h"
    #include "CWorkbooks.h"
    #include "CWorksheet.h"
    #include "CWorksheets.h"

    5.编译,会出现两个错误:

    …crange.h(335): warningC4003: “DialogBoxW”宏的实参不足

    …crange.h(335): errorC2059: 语法错误:“,”

    双击错误提示,定位在错误行,

    	VARIANT DialogBox()
    	{
    		VARIANT result;
    		InvokeHelper(0xf5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
    		return result;
    	}
    


    将该函数名“DialogBox()”前面加“_”下划线,即“_DialogBox()”,这样就可以编译成功了。


    6.在对话框中添加一个编辑框,并为其关联一CEdit类型变量m_Path,添加“打开”按钮,实现打开一已经存在的Excel文件。并将路径显示在编辑框中。


    实现代码如下。

     

    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);
    
    		//结尾,释放
    		book.ReleaseDispatch();   
    		books.ReleaseDispatch();   
    		app.ReleaseDispatch();
    		app.Quit();
    
    	}
    }
    

    7.在对话框中添加“写入”按钮,实现新建一Excel文件(存在则覆盖),并向文件中写入数据。实现代码如下。

    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());可代替上面一行
    	book = books.Add(covOptional);
    	//book.AttachDispatch(books.Add(covOptional),true); 可代替上面一行
    	sheets=book.get_Worksheets();
    	//sheets.AttachDispatch(book.get_Worksheets(),true); 可代替上面一行
    	sheet = sheets.get_Item(COleVariant((short)1));
    	//sheet.AttachDispatch(sheets.get_Item(_variant_t("sheet1")),true); 可代替上面一行
    	//下面两行,是向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!")));
    	
    	//下面是向第二行的前十个单元格中输入1到10,十个数字
    	for(long i=1;i<11;i++)
    		range.put_Item(_variant_t((long)2),_variant_t((long)i),_variant_t((long)i));
    
    	//设置列宽
    	range = sheet.get_Range(COleVariant(_T("A1")),COleVariant(_T("J1")));
    	range.put_ColumnWidth(_variant_t((long)5));
    
    	//显示表格
    	app.put_Visible(TRUE);
    
    	//保存
    	book.SaveCopyAs(COleVariant(strFile)); 
    	book.put_Saved(true);
    
    	//结尾,释放
    	book.ReleaseDispatch();   
    	books.ReleaseDispatch();   
    	app.ReleaseDispatch();
    	app.Quit(); 
    
    }

    8.在对话框中添加列表控件,并关联变量m_Grid,并设置显示为报表样式。在对话框中添加“写入列表”按钮,实现将对话框中已有的表写入到Excel中。实现代码如下。
    在初始化函数中,先初始化列表。

    //设置列表视图的扩展风格
    	m_Grid.SetExtendedStyle(LVS_EX_FLATSB			//扁平风格显示滚动条
    		|LVS_EX_FULLROWSELECT					//允许整行选中
    		|LVS_EX_HEADERDRAGDROP					//允许整列拖动
    		|LVS_EX_ONECLICKACTIVATE					//单击选中项
    		|LVS_EX_GRIDLINES);								//画出网格线
    	//设置表头
    	m_Grid.InsertColumn(0,_T("编号"),LVCFMT_LEFT,100,0);
    	m_Grid.InsertColumn(1,_T("姓名"),LVCFMT_LEFT,100,1);
    	m_Grid.InsertColumn(2,_T("所属部门"),LVCFMT_LEFT,100,2);
    	//向列表中插入数据
    	int count = 0;
    	m_Grid.InsertItem(count,_T("001"));	
    	m_Grid.SetItemText(count,1,_T("张一"));	
    	m_Grid.SetItemText(count++,2,_T("销售部"));
    	m_Grid.InsertItem(count,_T("002"));	
    	m_Grid.SetItemText(count,1,_T("列二"));	
    	m_Grid.SetItemText(count++,2,_T("研发部"));
    	m_Grid.InsertItem(count,_T("003"));	
    	m_Grid.SetItemText(count,1,_T("宇三"));	
    	m_Grid.SetItemText(count++,2,_T("采购部"));
    	m_Grid.InsertItem(count,_T("004"));	
    	m_Grid.SetItemText(count,1,_T("宙四"));	
    	m_Grid.SetItemText(count,2,_T("宣传部"));

    再编写按钮的响应函数

    void CExportToExcelDlg::OnBnClickedButtonWritelist()
    {
    	// TODO: 在此添加控件通知处理程序代码
    	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));
    	//得到全部Cells 
    	range.AttachDispatch(sheet.get_Cells()); 
    	CString sText[]={_T("编号"),_T("姓名"),_T("所属部门")};
    	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)));
    			}
    		}
    	}
    	//保存
    	book.SaveCopyAs(COleVariant(strFile)); 
    	book.put_Saved(true);
    	app.put_Visible(true); 
    	
    	//释放对象 
    	range.ReleaseDispatch(); 
    	sheet.ReleaseDispatch(); 
    	sheets.ReleaseDispatch(); 
    	book.ReleaseDispatch(); 
    	books.ReleaseDispatch();
    	app.ReleaseDispatch(); 
    	app.Quit(); 
    }

    效果图:




    按【打开】按钮,出现打开对话框,可选择Excel打开。



    按【写入】按钮,打开Excel文件。



    按下【写入列表】,打开Excel文件。



    引用文章:http://wenku.baidu.com/view/d7383548767f5acfa1c7cd30.html

  • 相关阅读:
    ubuntu下安装maven
    159.Longest Substring with At Most Two Distinct Characters
    156.Binary Tree Upside Down
    155.Min Stack
    154.Find Minimum in Rotated Sorted Array II
    153.Find Minimum in Rotated Sorted Array
    152.Maximum Product Subarray
    151.Reverse Words in a String
    150.Evaluate Reverse Polish Notation
    149.Max Points on a Line
  • 原文地址:https://www.cnblogs.com/riskyer/p/3310798.html
Copyright © 2011-2022 走看看