【MFC/C++操作Excel】Excel篇

MFC操作Excel

下面的操作基于Excel2003

一.初始化操作

1.导入类库

点击查看->建立类向导-> Add Class...\From a type Library...-> C:\Program Files\Microsoft Office\Office\EXCEL.EXE,接下来就可以看到导入的类excel.h, excel.cpp

2.初始化COM

找到AppInitInstance()函数,在其中添加 AfxOleInit()函数的调用,如:

       if (!AfxOleInit())

       {

              AfxMessageBox("注册COM出错!");

              return FALSE;

       }


 

二.我自己写的Excel操作类

ExcelOperate.h

#include "atlbase.h"
#include "excel.h"
using namespace myexcel;
class CExcelOperate  
{
private:
	myexcel::_Application m_ecApp;
	Workbooks m_ecBooks;
	_Workbook m_ecBook;
	Worksheets m_ecSheets;
	_Worksheet m_ecSheet;
	myexcel::Range m_ecRange;
	VARIANT ret;//保存单元格的值
public:
	CExcelOperate();
	virtual ~CExcelOperate();
public:
	//操作
    //**********************创建新EXCEL*******************************************
	BOOL CreateApp();
	BOOL CreateWorkbooks();                //创建一个新的EXCEL工作簿集合
    	BOOL CreateWorkbook();                //创建一个新的EXCEL工作簿
	BOOL CreateWorksheets();                //创建一个新的EXCEL工作表集合
    	BOOL CreateWorksheet(short index);                //创建一个新的EXCEL工作表
	BOOL CreateSheet(short index);
	BOOL Create(short index = 1);                         //创建新的EXCEL应用程序并创建一个新工作簿和工作表
    	void ShowApp();                        //显示EXCEL文档
    	void HideApp();                        //隐藏EXCEL文档
	//**********************打开文档*********************************************
	BOOL OpenWorkbook(CString fileName, short index = 1);
    	BOOL Open(CString fileName);        //创建新的EXCEL应用程序并打开一个已经存在的文档。
   	BOOL SetActiveWorkbook(short i);    //设置当前激活的文档。

    //**********************保存文档*********************************************
    	BOOL SaveWorkbook();                //Excel是以打开形式,保存。
    	BOOL SaveWorkbookAs(CString fileName);//Excel以创建形式,保存。
    	BOOL CloseWorkbook();
    	void CloseApp();
	//**********************读信息********************************
	BOOL GetRangeAndValue(CString begin, CString end);//得到begin到end的Range并将之间的值设置到ret中
	void GetRowsAndCols(long &rows, long &cols);//得到ret的行,列数
	BOOL GetTheValue(int rows, int cols, CString &dest);//返回第rows,cols列的值,注意只返回文本类型的,到dest中
	BOOL SetTextFormat(CString &beginS, CString &endS);//将beginS到endS设置为文本格式(数字的还要用下面的方法再转一次)
	BOOL SetRowToTextFormat(CString &beginS, CString &endS);//将beginS到endS(包括数字类型)设置为文本格式

};

 

ExcelOperate.cpp

CExcelOperate::CExcelOperate()
{

}

CExcelOperate::~CExcelOperate()
{

}

BOOL CExcelOperate::CreateApp()
{
    //if (FALSE == m_wdApp.CreateDispatch("Word.Application"))
	COleException pe;
	if (!m_ecApp.CreateDispatch(_T("Excel.Application"), &pe))
    {
        AfxMessageBox("Application创建失败,请确保安装了word 2000或以上版本!", MB_OK|MB_ICONWARNING);
		pe.ReportError();
		throw &pe;
        return FALSE;
    }
    return TRUE;
}

BOOL CExcelOperate::CreateWorkbooks()               //创建一个新的EXCEL工作簿集合
{
	if (FALSE == CreateApp()) 
    {
        return FALSE;
    }
    m_ecBooks = m_ecApp.GetWorkbooks();
    if (!m_ecBooks.m_lpDispatch) 
    {
        AfxMessageBox("WorkBooks创建失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
    return TRUE;
}

BOOL CExcelOperate::CreateWorkbook()               //创建一个新的EXCEL工作簿
{
	if(!m_ecBooks.m_lpDispatch) 
    {
        AfxMessageBox("WorkBooks为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }

    COleVariant vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

    m_ecBook = m_ecBooks.Add(vOptional);
	if(!m_ecBook.m_lpDispatch) 
    {
        AfxMessageBox("WorkBook为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
/*
    //得到document变量
    m_wdDoc = m_wdApp.GetActiveDocument();
    if (!m_wdDoc.m_lpDispatch) 
    {
        AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
    //得到selection变量
    m_wdSel = m_wdApp.GetSelection();
    if (!m_wdSel.m_lpDispatch) 
    {
        AfxMessageBox("Select获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
    //得到Range变量
    m_wdRange = m_wdDoc.Range(vOptional,vOptional);
    if(!m_wdRange.m_lpDispatch)
    {
        AfxMessageBox("Range获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
*/
    return TRUE;
}

BOOL CExcelOperate::CreateWorksheets()                //创建一个新的EXCEL工作表集合
{
	if(!m_ecBook.m_lpDispatch) 
    {
        AfxMessageBox("WorkBook为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	m_ecSheets = m_ecBook.GetSheets();
	if(!m_ecSheets.m_lpDispatch) 
    {
        AfxMessageBox("WorkSheets为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	return TRUE;
}

BOOL CExcelOperate::CreateWorksheet(short index)                //创建一个新的EXCEL工作表
{
	if(!m_ecSheets.m_lpDispatch) 
    {
        AfxMessageBox("WorkSheets为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	m_ecSheet = m_ecSheets.GetItem(COleVariant(index));
	if(!m_ecSheet.m_lpDispatch) 
    {
        AfxMessageBox("WorkSheet为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	return TRUE;
}

BOOL CExcelOperate::CreateSheet(short index)
{
	if(CreateWorksheets() == FALSE)
	{
			return FALSE;
	}
	if(CreateWorksheet(index) == FALSE)
	{
			return FALSE;
	}
	return TRUE;
}

BOOL CExcelOperate::Create(short index)                        //创建新的EXCEL应用程序并创建一个新工作簿和工作表
{
	if(CreateWorkbooks() == FALSE)
	{
		return FALSE;
	}
	if(CreateWorkbook() == FALSE)
	{
		return FALSE;
	}
	if(CreateSheet(index) == FALSE)
	{
		return FALSE;
	}
	return TRUE;
}

void CExcelOperate::ShowApp()                        //显示WORD文档
{
	m_ecApp.SetVisible(TRUE);
}

void CExcelOperate::HideApp()                       //隐藏word文档
{
	m_ecApp.SetVisible(FALSE);
}

//**********************打开文档*********************************************
BOOL CExcelOperate::OpenWorkbook(CString fileName, short index)
{
	if(!m_ecBooks.m_lpDispatch) 
    {
        AfxMessageBox("WorkSheets为空!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	//COleVariant vFileName(_T(fileName));
	COleVariant VOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
	m_ecBook = m_ecBooks.Open(fileName,VOptional, VOptional, VOptional, VOptional,VOptional, VOptional, VOptional, VOptional,VOptional, VOptional, VOptional, VOptional, VOptional, VOptional);
	if(!m_ecBook.m_lpDispatch) 
    {
        AfxMessageBox("WorkSheet获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	if(CreateSheet(index) == FALSE)
	{
		return FALSE;
	}
	return TRUE;
}

BOOL CExcelOperate::Open(CString fileName)        //创建新的EXCEL应用程序并打开一个已经存在的文档。
{
	if(CreateWorkbooks() == FALSE)
	{
		return FALSE;
	}
	return OpenWorkbook(fileName);
}

/*BOOL CExcelOperate::SetActiveWorkbook(short i)    //设置当前激活的文档。
{
}*/

//**********************保存文档*********************************************
BOOL CExcelOperate::SaveWorkbook()                //文档是以打开形式,保存。
{
	if (!m_ecBook.m_lpDispatch) 
    {
        AfxMessageBox("Book获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	m_ecBook.Save();
	return TRUE;
}
BOOL CExcelOperate::SaveWorkbookAs(CString fileName)//文档以创建形式,保存。
{
	if (!m_ecBook.m_lpDispatch) 
    {
        AfxMessageBox("Book获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
    COleVariant vTrue((short)TRUE),    
                vFalse((short)FALSE),
                vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    COleVariant vFileName(_T(fileName));

    m_ecBook.SaveAs(
                vFileName,    //VARIANT* FileName
                vOptional,    //VARIANT* FileFormat
                vOptional,    //VARIANT* LockComments
                vOptional,    //VARIANT* Password
                vOptional,    //VARIANT* AddToRecentFiles
                vOptional,    //VARIANT* WritePassword
                0,    //VARIANT* ReadOnlyRecommended
                vOptional,    //VARIANT* EmbedTrueTypeFonts
                vOptional,    //VARIANT* SaveNativePictureFormat
                vOptional,    //VARIANT* SaveFormsData
                vOptional,    //VARIANT* SaveAsAOCELetter
				vOptional    //VARIANT* ReadOnlyRecommended
/*                vOptional,    //VARIANT* EmbedTrueTypeFonts
                vOptional,    //VARIANT* SaveNativePictureFormat
                vOptional,    //VARIANT* SaveFormsData
                vOptional    //VARIANT* SaveAsAOCELetter*/
                );
    return    TRUE;
}
BOOL CExcelOperate::CloseWorkbook()
{
	COleVariant vTrue((short)TRUE),    
                vFalse((short)FALSE),
                vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
	
    m_ecBook.Close(vFalse,    // SaveChanges.
             vTrue,            // OriginalFormat.
             vFalse            // RouteDocument.
             );
	m_ecBook = m_ecApp.GetActiveWorkbook();
	if(!m_ecBook.m_lpDispatch) 
    {
        AfxMessageBox("Book获取失败!", MB_OK|MB_ICONWARNING);
        return FALSE;
    }
	if(CreateSheet(1) == FALSE)
	{
		return FALSE;
	}
	return TRUE;
}
void CExcelOperate::CloseApp()
{
	SaveWorkbook();
	COleVariant vTrue((short)TRUE),    
                vFalse((short)FALSE),
                vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    //m_ecDoc.Save();
    m_ecApp.Quit();
	if(m_ecRange.m_lpDispatch)
		m_ecRange.ReleaseDispatch();
	if(m_ecSheet.m_lpDispatch)
		m_ecSheet.ReleaseDispatch();
	if(m_ecSheets.m_lpDispatch)
		m_ecSheets.ReleaseDispatch();
	if(m_ecBook.m_lpDispatch)
		m_ecBook.ReleaseDispatch();
	if(m_ecBooks.m_lpDispatch)
		m_ecBooks.ReleaseDispatch();
	if(m_ecApp.m_lpDispatch)
		m_ecApp.ReleaseDispatch();

}

BOOL CExcelOperate::GetRangeAndValue(CString begin, CString end)
{
	if(!m_ecSheet.m_lpDispatch)
	{
		AfxMessageBox("Sheet获取失败!", MB_OK|MB_ICONWARNING);
		return FALSE;
	}
	m_ecRange = m_ecSheet.GetRange(COleVariant(begin), COleVariant(end));
	if(!m_ecRange.m_lpDispatch)
	{
		AfxMessageBox("Range获取失败!", MB_OK|MB_ICONWARNING);
		return FALSE;
	}
	ret = m_ecRange.GetValue2();//得到表格中的值
	return TRUE;
}

void CExcelOperate::GetRowsAndCols(long &rows, long &cols)
{
	COleSafeArray sa(ret);
	sa.GetUBound(1,&rows);
	sa.GetUBound(2,&cols);
}

//只返回CString类型的,其他类型概视为错误
BOOL CExcelOperate::GetTheValue(int rows, int cols, CString &dest)
{
	long rRows, rCols;
	long index[2];
	VARIANT val;
	COleSafeArray sa(ret);
	sa.GetUBound(1,&rRows);
	sa.GetUBound(2,&rCols);
	if(rows < 1 || cols < 1 || rRows < rows || rCols < cols)
	{
		AfxMessageBox("出错点1");
		return FALSE;
	}
	index[0]=rows;
	index[1]=cols;	
	sa.GetElement(index,&val);
	if(val.vt != VT_BSTR)
	{
		CString str;
		str.Format("出错点2, %d",val.vt);
		AfxMessageBox(str);
		return FALSE;
	}
	dest = val.bstrVal;
	return TRUE;
}

//将beginS到endS之间设置为文本格式
BOOL CExcelOperate::SetTextFormat(CString &beginS, CString &endS)
{
	if(GetRangeAndValue(beginS, endS))
	{
		m_ecRange.Select();
		m_ecRange.SetNumberFormatLocal(COleVariant("@"));
		return TRUE;
	}
	return FALSE;
}

//将beginS到endS之间(必须是一列)设置为真正的文本格式
BOOL CExcelOperate::SetRowToTextFormat(CString &beginS, CString &endS)
{
	if(GetRangeAndValue(beginS, endS))
	{
		m_ecRange.Select();
		Range m_tempRange = m_ecSheet.GetRange(COleVariant(beginS), COleVariant(beginS));
		if(!m_tempRange.m_lpDispatch) return FALSE;
		COleVariant vTrue((short)TRUE),    
                vFalse((short)FALSE);
		//int tempArray[2] = {1, 2};
		COleSafeArray saRet;
		DWORD numElements = {2};
		saRet.Create(VT_I4, 1, &numElements);
		long index = 0;
		int val = 1;
		saRet.PutElement(&index, &val);
		index++;
		val = 2;
		saRet.PutElement(&index, &val);
		//m_tempRange.GetItem(COleVariant((short)5),COleVariant("A"));
		m_ecRange.TextToColumns(m_tempRange.GetItem(COleVariant((short)1),COleVariant((short)1)), 1, 1, vFalse, vTrue, vFalse, vFalse, vFalse, vFalse, vFalse, saRet, vFalse, vFalse, vTrue);
		m_tempRange.ReleaseDispatch();
		return TRUE;
	}
	return FALSE;
}



 

你可能感兴趣的:(MFC操作office)