VC++ 操作EXCEL

#include "StdAfx.h"
#include "QVExcel.h"
#include "excel9.h"

#ifndef LKEXCEL_PARAMETER
#define LKEXCEL_PARAMETER

/* xls format parameter */
#define EXCEL_FMT_XLS	1
#define EXCEL_STR_XLS	".xls"
#define EXCEL_ROW_XLS	65536
#define EXCEL_COL_XLS	256

/* xlsx format parameter */ 

#define EXCEL_FMT_XLSX	2
#define EXCEL_STR_XLSX	".xlsx"
#define EXCEL_ROW_XLSX	1048576
#define EXCEL_COL_XLSX	16384


#endif

/* Define class CExcelOption */
class CExcelOption
{
private:
	bool			m_bInitialize;	/* True for variables initialized, else false */
	bool			m_bOpenExcel;	/* True for excel opened, else false */
	int				m_nSheetCount;	/* Sheet count of current excel file */
	int				m_nCurSheet;	/* Index of current sheet */
	int				m_nFileFormat;	/* File format to save */
	int				m_nMaxRowCount;	/* Maximum count of rows in a sheet */
	int				m_nMaxColCount;	/* Maximum count of columns in a sheet */
	CString			m_sFileName;	/* File name to save */	

	_Application	m_ExcelApp;		/* Excel application */
	Workbooks		m_ExcelBook;	/* Excel books */
	Sheets			m_ExcelSheet;	/* Excel sheets */
	_Workbook		m_WorkBook;		/* Current book */
	_Worksheet		m_WorkSheet;	/* Current sheet */
	Range			m_Range;		/* Range to read or write */
	LPDISPATCH		m_lpDisp;      //打开excel得到的句柄
	// 获得使用的行数
	long m_UsedRowNum;
	// 获得使用的列数
	long m_UsedColumnNum;
	/* Initialize variable */
	void Initialize();
	/* Release memory */
	void Release();
	/* Check out file name */
	bool CheckFileName(TCHAR * pFileName,bool bWrite);
public:
	/* Construction function */
	CExcelOption();
	/* Destruction function */
	~CExcelOption();
	/* Open an existing file or create a new file */
	int Open(TCHAR * pFileName, bool bWrite,int sheet);
	/* Add a new sheet and set it as current sheet */
	int AddSheet(TCHAR* pName, bool bBack);
	/* Select a sheet and set it as current sheet */
	int SelectSheet(int nSheetIndex);
	/* Write a cell */
	int WriteCell(int nRow, int nColumn, char* pData);
	/* Write a cell with font property */
	int WriteProCell(int nRow, 
					 int nColumn, 
					 TCHAR* pData,  
					 long clr = RGB(0,0,0), 					 
					 bool bBold = false,
					 bool bItalic = false,
					 TCHAR *chName = NULL,
					 int nSize=-1			/* default font size */
					 );
	/* modify current sheet column width */
	int SetColWidth(int nCol, int nWidth);
	/* Read a cell */
	int ReadCell(int nRow, int nColumn, char ** pData);
	/* Close excel file */
	int Close(bool bNeedSave = true);
	//读excel数据,待改善
	int ReadCellFromExcel(int nRow, int nColumn, CStringArray* arrayStr,bool Flag);
} ExcelOption; /* Global variable */

/************************************************************************/
/* Implement of class CLKExecelOption                                   */
/************************************************************************/
CQVExcel::CQVExcel(void)
{
}

CQVExcel::~CQVExcel(void)
{
}

/******************************************************************
Name        : Open
Description	: check out the file name and open excel application
Par	 	    : pFileName[in]: file's full name 
			  bWrite[in] : true for writing, false for reading
Return      : return 0 if success, else -1
Remarks     : invoke function Close(bool bNeedSave)
******************************************************************/
int CQVExcel::Open(TCHAR * pFileName, bool bWrite,int sheet)
{
	return ExcelOption.Open(pFileName, bWrite,sheet);
}

/******************************************************************
Name        : AddSheet
Description	: add a excel sheet to current excel book
Par	 	    : pSheetName[in]: file's full name 
			  bBack[in]		: true for add a sheet back current sheet, else for before
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CQVExcel::AddSheet(TCHAR* pSheetName, bool bBack)
{
	return ExcelOption.AddSheet(pSheetName, bBack);
}

/******************************************************************
Name        : SelectSheet
Description	: select a sheet as current sheet to operate
Par	 	    : nSheetIndex[in]: index of sheet to select 
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CQVExcel::SelectSheet(int nSheetIndex)
{
	return ExcelOption.SelectSheet(nSheetIndex);
}

/* Write a cell without font color */
int CQVExcel::WriteCell(int nRow, int nColumn, char* pData)
{
	return ExcelOption.WriteCell(nRow, nColumn, pData);
}

/******************************************************************
Name        : WriteProCell
Description	: write a cell to current sheet
Par	 	    : nRow[in]		: index of row
			  nColumn[in]	: index of column
			  pData[in]		: buffer of data to write
			  clr[in] : current cell string color
			  bBold[in] : if current cell string is bold
			  bItalic[in] : if current cell string is italic
			  chName[in] : current cell string font name
			  nSize[in] : current cell font size
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CQVExcel::WriteProCell(int nRow, 
								 int nColumn, 
								 TCHAR* pData,  
								 long clr/* = RGB(0,0,0)*/, 								 
								 bool bBold/* = false*/,
								 bool bItalic/* = false*/,
								 TCHAR *chName/* = NULL*/,
								 int nSize/*=-1*/			/* default font size */
								 )
{
	return ExcelOption.WriteProCell(nRow, nColumn, pData, clr, bBold, bItalic, chName, nSize);
}

/******************************************************************
Name        : SetColWidth
Description	: modify current sheet column width
Par	 	    :
			nCol[in]	: index of column
			nWidth[in]  : column width 
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CQVExcel::SetColWidth(int nCol, int nWidth)
{
	return ExcelOption.SetColWidth(nCol, nWidth);
}

/******************************************************************
Name        : ReadCell
Description	: read a cell from current sheet
Par	 	    : nRow[in]		: index of row
			  nColumn[in]	: index of column
			  pData[out]	: pointer of buffer to store the data
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CQVExcel::ReadCell(int nRow, int nColumn, char** pData)
{
	return ExcelOption.ReadCell(nRow, nColumn, pData);
}
//测试用
int CQVExcel::ReadCellFromExcel(int nRow, int nColumn, CStringArray* arrayStr,bool Flag)
{
	return ExcelOption.ReadCellFromExcel(nRow,nColumn,arrayStr,Flag);
}


/******************************************************************
Name        : Close
Description	: save file and close excel application
Par	 	    : bNeedSave[in]: true for save file, else for not save 
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CQVExcel::Close(bool bNeedSave)
{
	return ExcelOption.Close(bNeedSave);
}

/************************************************************************/
/* Implement of class CExecelOption                                     */
/************************************************************************/

COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR), 
			vtTrue((short)TRUE),
			vtFalse((short)FALSE);

CExcelOption::CExcelOption()
{
	m_bOpenExcel	= false;
	m_bInitialize	= false;
	m_nCurSheet		= 0;
	m_nMaxColCount	= 0;
	m_nMaxRowCount	= 0;
}

CExcelOption::~CExcelOption()
{
	Release();
}

/******************************************************************
Name        : Initialize
Description	: Initialize variable
Par	 	    : void 
Return      : void
Remarks     : none
******************************************************************/
void CExcelOption::Initialize()
{
	if(!m_bInitialize){
		/* Do this if it has not been initialized */
		m_nSheetCount = 0;
		m_nCurSheet = 0;
		m_bOpenExcel = false;
		m_bInitialize = true;
		CoInitialize(NULL);
	}
}

/******************************************************************
Name        : Release
Description	: release memory
Par	 	    : void 
Return      : void
Remarks     : none
******************************************************************/
void CExcelOption::Release()
{
	if(m_bOpenExcel){	
		/* Do this if excel application has been opened */
		m_Range.ReleaseDispatch();
		m_WorkSheet.ReleaseDispatch();
		m_WorkBook.ReleaseDispatch();
		m_ExcelSheet.ReleaseDispatch();
		m_ExcelBook.ReleaseDispatch();		
		/* Exit Excel.Application */
		m_ExcelApp.Quit();
		m_ExcelApp.ReleaseDispatch();
		m_bOpenExcel = false;		
	}
	if(m_bInitialize){
		/* Do this if it has been initialized */
		CoUninitialize();
		m_bInitialize = false;
	}
}

/******************************************************************
Name        : CheckFileName
Description	: check out the file name
Par	 	    : pFileName[in]: file's full name 
			: bWrite[in] : true for writing, false for reading
Return      : return true if success, else false
Remarks     : none
******************************************************************/
bool CExcelOption::CheckFileName(TCHAR * pFileName,bool bWrite)
{
	CString sFileName = pFileName;
	CString sFileEx;
//	if(do something with file path here)
	int nLength = sFileName.GetLength();
	int nTag = sFileName.ReverseFind('.');
	if(nTag < 0){
		m_nFileFormat = EXCEL_FMT_XLS;		
	}else{
		sFileEx = sFileName.Right(nLength - nTag - 1);
		sFileName = sFileName.Left(nTag);
//		if(do something with sFileEx here)
		if (sFileEx.CompareNoCase(_T("xlsx")))
		{
			m_nFileFormat = EXCEL_FMT_XLSX;
		}			
		else
		{
			m_nFileFormat = EXCEL_FMT_XLS;
		}
	}
	switch(m_nFileFormat){
		case EXCEL_FMT_XLS:
			sFileEx = EXCEL_STR_XLS;
			m_nMaxRowCount = EXCEL_ROW_XLS;
			m_nMaxColCount = EXCEL_COL_XLS;
			break;
		case EXCEL_FMT_XLSX:
			sFileEx = EXCEL_STR_XLSX;
			m_nMaxRowCount = EXCEL_ROW_XLSX;
			m_nMaxColCount = EXCEL_COL_XLSX;
			break;
		default:
			break;
	}
	m_sFileName = sFileName + sFileEx;
	if (bWrite==TRUE)
	{
		::DeleteFile(m_sFileName);
	}

// 	CFile file;
// 	if(file.Open(m_sFileName, CFile::modeCreate | CFile::modeReadWrite) == NULL){
// 		/* return false if create file failed */
// 		return false;
// 	}
// 	file.Close();	
	return true;
}

/******************************************************************
Name        : Open
Description	: check out the file name and open excel application
Par	 	    : pFileName[in]: file's full name 
			  bWrite[in] : true for writing, false for reading
Return      : return 0 if success, else -1
Remarks     : invoke function Close(bool bNeedSave)
******************************************************************/
int CExcelOption::Open(TCHAR * pFileName, bool bWrite,int sheet)
{
	int nResult = -1;
	if(!m_bOpenExcel){
		/* Do this if excel application has not been opened */		
		if(CheckFileName(pFileName,bWrite)){		
			/* Initialize variable */
			Initialize();		
			if(NULL != m_ExcelApp.CreateDispatch(_T("excel.application"), NULL)){	
				m_bOpenExcel = true;
				nResult = 0;
				if (bWrite==TRUE)
				{
					try{
						m_ExcelApp.SetVisible(FALSE);		/* hide excel instrance UI */
						m_ExcelApp.SetUserControl(TRUE);	/* allowed other user to control excel */
						m_ExcelApp.SetSheetsInNewWorkbook(1);			
						m_ExcelBook  = m_ExcelApp.GetWorkbooks();
						m_ExcelSheet = m_ExcelBook.Add(vtOptional);
						m_WorkBook.AttachDispatch(m_ExcelApp.GetApplication());
						m_ExcelSheet = m_WorkBook.GetSheets();
						m_WorkSheet = m_ExcelSheet.GetItem(COleVariant((short)1));			
						m_Range = m_WorkSheet.GetCells();
					}catch (CException* e){
						e->Delete();
						nResult = -1;
						Release();					
					}
				}
				else
				{
					COleVariant
						covTrue((short)TRUE),
						covFalse((short)FALSE),
						covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
					//设置为显示
					m_ExcelApp.SetVisible(FALSE);
					m_ExcelBook.AttachDispatch( m_ExcelApp.GetWorkbooks(), TRUE ); //没有这条语句,下面打开文件返回失败。
					// 打开文件
					m_lpDisp = m_ExcelBook.Open( pFileName,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional,
						covOptional);
						if (m_lpDisp==NULL)
						{
							return -1;
						}
						// 获得活动的WorkBook( 工作簿 )
						m_WorkBook.AttachDispatch( m_lpDisp, TRUE );
						m_ExcelSheet = m_WorkBook.GetWorksheets();        //得到Worksheets
						m_WorkSheet = m_ExcelSheet.GetItem(COleVariant((short)sheet)); //得到Worksheet 
						// 获得活动的WorkSheet( 工作表 )
						//m_WorkSheet.AttachDispatch( m_WorkBook.GetActiveSheet(), TRUE );
						// 获得使用的区域Range( 区域 )
						m_Range.AttachDispatch( m_WorkSheet.GetUsedRange(), TRUE );

						m_Range.AttachDispatch( m_Range.GetRows(), TRUE );
						m_UsedRowNum = m_Range.GetCount();

						m_Range.AttachDispatch( m_Range.GetColumns(), TRUE );
						m_UsedColumnNum = m_Range.GetCount();
						// 读取Sheet的名称
						CString strSheetName = m_WorkSheet.GetName();
						//得到全部Cells,此时,CurrRange是cells的集合
						m_Range.AttachDispatch( m_WorkSheet.GetCells(), TRUE );

				}
			
			}else{
				Release();
			}
		}
	}

	return nResult;
}

/******************************************************************
Name        : AddSheet
Description	: add a excel sheet to current excel book
Par	 	    : pSheetName[in]: file's full name 
bBack[in]		: true for add a sheet back current sheet, else for before
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CExcelOption::AddSheet(TCHAR* pSheetName, bool bBack)
{	
	int nResult = -1;
	while(m_bOpenExcel){
		/* Do this if excel application has been opened */
		try{
			if(m_nSheetCount > 0){
				/* Not first time to add sheet */
				VARIANT vtTag;
				vtTag.vt = VT_DISPATCH;
				/* Get current sheet as a tag */
				vtTag.pdispVal = m_ExcelSheet.GetItem(COleVariant((short)m_nCurSheet));		
				if(bBack){
					/* Add sheet after current sheet */
					m_WorkSheet = m_ExcelSheet.Add(vtOptional, vtTag,vtOptional,vtOptional);
				}else{
					/* Add sheet before current sheet */
					m_WorkSheet = m_ExcelSheet.Add(vtTag, vtOptional,vtOptional,vtOptional);
				}
				/* Release vtTag */
				vtTag.pdispVal->Release();
			}else{
				/* First time to add sheet */
				m_WorkSheet = m_ExcelSheet.GetItem(COleVariant((short)1));
				m_nCurSheet = 1;
			}
		}catch (CException* e){
			e->Delete();
			break;
		}
		try{			
			CString sSheetName = pSheetName;
			if(!sSheetName.IsEmpty()){
				/* string number can't be great or equal 32 */
				if (sSheetName.GetLength() >= 32) {
					sSheetName = sSheetName.Left(31);
				}
				/* Set sheet name */
				m_WorkSheet.SetName(sSheetName);
			}
			/* Get range to operate */
			m_Range = m_WorkSheet.GetCells();
		}	
		catch (CException* e){
			e->Delete();
			/* Delete sheet if set name failed or get range failed */
			m_WorkSheet.Delete();
			break;		
		}	
		/* Set index of current sheet */	
		if(bBack && m_nSheetCount++ > 0){			
			m_nCurSheet ++;
		}
		nResult = 0;
		break;
	}
	return nResult;
}

/******************************************************************
Name        : SelectSheet
Description	: select a sheet as current sheet to operate
Par	 	    : nSheetIndex[in]: index of sheet to select 
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CExcelOption::SelectSheet(int nSheetIndex)
{
#if 0
	int nResult = -1;
	while(m_bOpenExcel){
		/* Do this if excel application has been opened */
		try{
			/* Select sheet and range */
			m_WorkSheet = m_ExcelSheet.GetItem(COleVariant((short)(nSheetIndex)));
			m_Range = m_WorkSheet.GetCells();
		}catch (CException* e){
			e->Delete();
			break;		
		}
		/* Set index of current sheet */
		m_nCurSheet = nSheetIndex;
		nResult = 0;
		break;
	}	
	return nResult;
#endif
#if 0
	int nResult = -1;
	if (m_lpDisp==NULL)
	{
		return -1;
	}
	while (m_bOpenExcel)
	{
		try{
		// 获得活动的WorkBook( 工作簿 )
		m_WorkBook.AttachDispatch( m_lpDisp, TRUE );
		// 获得活动的WorkSheet( 工作表 )
		m_WorkSheet.AttachDispatch( m_WorkBook.GetActiveSheet(), TRUE );
		// 获得使用的区域Range( 区域 )
		//m_Range.AttachDispatch( m_WorkSheet.GetUsedRange(), TRUE );
		}catch (CException* e){
			e->Delete();
			break;		
		}
	}
	return nResult;
#endif
	return -1;
}

/******************************************************************
Name        : WriteCell
Description	: write a cell to current sheet
Par	 	    : nRow[in]		: index of row
			  nColumn[in]	: index of column
			  pData[in]		: buffer of data to write
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CExcelOption::WriteCell(int nRow, int nColumn, char* pData)
{
	if(m_nCurSheet < 1 || nRow > m_nMaxRowCount || nRow < 1
		|| nColumn > m_nMaxColCount || nColumn < 1){
		/* condition checking */
		return -1;
	}	
	CString sData;
	sData = pData;
	/* Write data to range */
	m_Range.SetItem(COleVariant((long)nRow),COleVariant((long)nColumn),COleVariant(sData));
	return 0;
}


/* Write a cell with font property */
int CExcelOption::WriteProCell(int nRow, 
							   int nColumn, 
							   TCHAR* pData,  
							   long clr/* = RGB(0,0,0)*/, 							   
							   bool bBold/* = false*/,
							   bool bItalic/* = false*/,
							   TCHAR *chName/* = NULL*/,
							   int nSize/*=-1*/			/* default font size */
							   )
{
	if(m_nCurSheet < 1 || nRow > m_nMaxRowCount || nRow < 1
	|| nColumn > m_nMaxColCount || nColumn < 1) {
		/* condition checking */
		return -1;
	}
	
	CString sData = pData;
	/* Write data to range */
	m_Range.SetItem(COleVariant((long)nRow),COleVariant((long)nColumn),COleVariant(sData));	
	
	/* Set font property */
	CExcelFont font; 
	m_Range.AttachDispatch((m_Range.GetItem(COleVariant(long(nRow)), COleVariant(long(nColumn)))).pdispVal); 
	font.AttachDispatch(m_Range.GetFont());
	font.SetColor(COleVariant((long)clr));
	font.SetBold(COleVariant((short)bBold));
	font.SetItalic(COleVariant((short)bItalic));

	if (chName != NULL) {

		CString strTemp = chName;
		font.SetName(COleVariant(strTemp));
	}
	if (nSize != -1) {
		font.SetSize(COleVariant((short)nSize));
	}

	/* restore work sheet */
	m_Range = m_WorkSheet.GetCells();

	return 0;
}

/******************************************************************
Name        : SetColWidth
Description	: modify current sheet column width
Par	 	    :
			nCol[in]	: index of column
			nWidth[in]  : column width 
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CExcelOption::SetColWidth(int nCol, int nWidth)
{
	/* condition checking */
	if(m_nCurSheet < 1 || nCol > m_nMaxColCount || nCol < 1) {			
		return -1;
	}

	/* Set column width */
	m_Range.AttachDispatch((m_Range.GetItem(COleVariant(long(1)), COleVariant(long(nCol)))).pdispVal); 
	m_Range.SetColumnWidth(COleVariant(short(nWidth)));
	
	/* restore work sheet */
	m_Range = m_WorkSheet.GetCells();

	return 0;
}

/******************************************************************
Name        : ReadCell
Description	: read a cell from current sheet
Par	 	    : nRow[in]		: index of row
nColumn[in]	: index of column
pData[out]	: pointer of buffer to store the data
Return      : return 0 if success, else -1
Remarks     : delete pData after use
******************************************************************/
int CExcelOption::ReadCell(int nRow, int nColumn, char** pData)
{
	if(m_nCurSheet < 1 || pData == NULL || nRow > m_nMaxRowCount 
		|| nRow < 1	|| nColumn > m_nMaxColCount || nColumn < 1){
			/* condition checking */
			return -1;
	}
// 	sheets.AttachDispatch(lpDisp);
// 	lpDisp=sheets.get_Item(COleVariant((short)(k)));//取得第一个工作表
// 	sheets.AttachDispatch(lpDisp);
#if 0
		m_WorkBook.AttachDispatch( m_lpDisp, TRUE );
		m_WorkSheet = m_ExcelSheet.GetItem(COleVariant((short)(1)));
#endif
	// 获得活动的WorkBook( 工作簿 )
	m_WorkBook.AttachDispatch( m_lpDisp, TRUE );
	// 获得活动的WorkSheet( 工作表 )
	m_WorkSheet.AttachDispatch( m_WorkBook.GetActiveSheet(), TRUE );
	// 获得使用的区域Range( 区域 )
	m_Range.AttachDispatch( m_WorkSheet.GetUsedRange(), TRUE );
	// 获得使用的行数
	long lgUsedRowNum = 0;
	m_Range.AttachDispatch( m_Range.GetRows(), TRUE );
	lgUsedRowNum = m_Range.GetCount();
	// 获得使用的列数
	long lgUsedColumnNum = 0;
	m_Range.AttachDispatch( m_Range.GetColumns(), TRUE );
	lgUsedColumnNum = m_Range.GetCount();
	// 读取Sheet的名称
	CString strSheetName = m_WorkSheet.GetName();
	//得到全部Cells,此时,CurrRange是cells的集合
	m_Range.AttachDispatch( m_WorkSheet.GetCells(), TRUE );
	// 遍历整个Excel表格
	CStringArray* arrayStr;
	arrayStr = new CStringArray[lgUsedRowNum];
	Range  oCurCell;
	for ( int i = 0; i < lgUsedRowNum; )
	{
		for ( int j = 1; j <= lgUsedColumnNum; )
		{
			oCurCell.AttachDispatch( m_Range.GetItem( COleVariant( (long)(i + 1)), COleVariant( (long)j ) ).pdispVal, TRUE );
			VARIANT varItemName = oCurCell.GetText();
			CString strItemName;
			strItemName = varItemName.bstrVal;
			//         AfxMessageBox( strItemName );
			// 判断是否是合并的单元格
			VARIANT varMerge = oCurCell.GetMergeCells();
			if ( varMerge.boolVal == -1 )
			{
				//             AfxMessageBox( _T( "是合并的单元格!" ) );
			}
			else if ( varMerge.boolVal == 0 )
			{
				//             AfxMessageBox( _T( "不是合并的单元格!" ) );
			}

			arrayStr[i].Add( strItemName );
			j++;
		}
		i++;
	}
	return -1;
}
//读excel数据,针对这个版本 Flag = true表示读取产品型号 false表示根据产品型号读配置
int CExcelOption::ReadCellFromExcel(int nRow, int nColumn, CStringArray* arrayStr,bool Flag)
{
	Range  oCurCell;
	//读产品型号 列固定
	if (Flag==TRUE)
	{
		for ( int i = 1; i < m_UsedRowNum;++i)
		{
			oCurCell.AttachDispatch( m_Range.GetItem( COleVariant( (long)(i + 1)), COleVariant( (long)nColumn ) ).pdispVal, TRUE );
			VARIANT varItemName = oCurCell.GetText();
			CString strItemName;
			strItemName = varItemName.bstrVal;
			// 判断是否是合并的单元格
			VARIANT varMerge = oCurCell.GetMergeCells();
			if ( varMerge.boolVal == -1 )
			{
				//             AfxMessageBox( _T( "是合并的单元格!" ) );
			}
			else if ( varMerge.boolVal == 0 )
			{
				//             AfxMessageBox( _T( "不是合并的单元格!" ) );
			}

			arrayStr->Add( strItemName );
			int k = arrayStr->GetSize();
		}
		
	}
	else//根据所选的产品型号读取配置信息 行固定 
	{
		for ( int i = 1; i < m_UsedColumnNum-1;++i)
		{
			oCurCell.AttachDispatch( m_Range.GetItem( COleVariant( (long)(nRow+2)), COleVariant( (long)i+2 ) ).pdispVal, TRUE );
			VARIANT varItemName = oCurCell.GetText();
			CString strItemName;
			strItemName = varItemName.bstrVal;
			//如果取到的数据为空就赋值为0
			if ((strItemName.CompareNoCase(_T(""))==0))
			{
				strItemName = "0";
			}
			// 判断是否是合并的单元格
			VARIANT varMerge = oCurCell.GetMergeCells();
			if ( varMerge.boolVal == -1 )
			{
				//             AfxMessageBox( _T( "是合并的单元格!" ) );
			}
			else if ( varMerge.boolVal == 0 )
			{
				//             AfxMessageBox( _T( "不是合并的单元格!" ) );
			}

			arrayStr->Add( strItemName );
			int k = arrayStr->GetSize();
		}
		
	}

	return 0;
}

/******************************************************************
Name        : Close
Description	: save file and close excel application
Par	 	    : bNeedSave[in]: true for save file, else for not save 
Return      : return 0 if success, else -1
Remarks     : none
******************************************************************/
int CExcelOption::Close(bool bNeedSave)
{
	int nResult = -1;
	if (bNeedSave == TRUE)
	{
		while(m_bOpenExcel){
			/* Do this if excel application has been opened */
			try{
				/* Delete old file */
				::DeleteFile(m_sFileName);
				/* Write to excel file */			
				m_WorkSheet = m_ExcelSheet.GetItem(COleVariant((short)(1)));
				m_WorkSheet.SaveAs(m_sFileName, vtOptional, vtOptional, vtOptional, vtOptional,
					vtOptional, vtOptional, vtOptional, vtOptional);
			}
			catch (CException* e){
				e->Delete();
				break;
			}		
			nResult = 0;	
			break;
		}
		/* Release memory */
		Release();
		m_nCurSheet = 0;
	}
	else
	{
		/* Release memory */
		Release();
		m_nCurSheet = 0;
		/* Delete file if no need save*/
		::DeleteFile(m_sFileName);
	}
	return nResult;
}

=================================================================================================================

程序猿和程序媛必备的咖啡-OneDay咖啡生活-https://shop110384469.taobao.com/



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【前言】 工作或学习中可能需要实现基于VC读\写Excel文件的功能,本人最近也遇到了该问题。中间虽经波折,但是最终还是找到了解决问题的办法。 在此跟大家分享,希望对跟我同样迷茫过的同学们有所帮助。 1、程序功能 1)打开一个excel文件; 2)显示到CListCtrl上; 3)新建一个Excel文件。 以上均在对话框中实现。 2、平台 VC++2010 3、实现方法 常用的Excel打开方式有两种 1)通过数据库打开; 2)OLE方式打开。 由于方式1)操作繁琐,经常出现莫名的错误,这里选用方式2). 4、准备步骤 首先新建一个Dialog窗体程序,添加list control和两个按钮 1)将ExcelLib文件夹拷贝到程序目录下; 2)将Export2Excel.h,Export2Excel.cpp两个文件添加到项目; 3)包含头文件,#include "ExcelLib/Export2Excel.h" 通过以上步骤在程序中引入了可以读取Excle文件的CExport2Excel; 5、打开excel文件 通过按钮点击打开 void CExcelTestDlg::OnBnClickedButtonOpenExcel() { //获取文件路径 CFileDialog* lpszOpenFile; CString szGetName; lpszOpenFile = new CFileDialog(TRUE,"","",OFN_FILEMUSTEXIST|OFN_HIDEREADONLY,"Excel File(*.xlsx;*.xls)|*.xls;*.xlsx",NULL); if (lpszOpenFile->DoModal()==IDOK) { szGetName = lpszOpenFile->GetPathName(); SetWindowText(szGetName); delete lpszOpenFile; } else return; //打开文件 //文件中包含多个sheet时,默认打开第一个sheet CExport2Excel Excel_example; Excel_example.OpenExcel(szGetName); //获取sheet个数 int iSheetNum = Excel_example.GetSheetsNumber(); //获取已使用表格行列数 int iRows = Excel_example.GetRowCount(); int iCols = Excel_example.GetColCount(); //获取单元格的内容 CString cs_temp = Excel_example.GetText(1,1); //AfxMessageBox(cs_temp); //List control上显示 //获取工作表列名(第一行) CStringArray m_HeadName; m_HeadName.Add(_T("ID")); for (int i=1;iGetItemCount()>0) { m_list.DeleteColumn(0); } //初始化ClistCtrl,加入列名 InitList(m_list,m_HeadName); //填入内容 //第一行是标题,所以从第2行开始 CString num; int pos; for (int row = 2;row<=iRows; row++) { pos = m_list.GetItemCount(); num.Format(_T("%d"),pos +1); m_list.InsertItem(pos,num); for (int colum=1;columDoModal()==IDOK) { szGetName = lpszOpenFile->GetPathName(); SetWindowText(szGetName); delete lpszOpenFile; } else return; //文件全名称 CString csFileName = szGetName; //需要添加的两个sheet的名称 CString csSheetName = "newSheet"; CString csSheetName2 = "newSheet2"; // 新建一个excel文件,自己写入文字 CExport2Excel Excel_example; //新建excel文件 Excel_example.CreateExcel(csFileName); //添加sheet,新加的sheet在前,也就是序号为1 Excel_example.CreateSheet(csSheetName); Excel_example.CreateSheet(csSheetName2); //操作最开始添加的sheet:(newSheet) Excel_example.SetSheet(2); //添加表头 Excel_example.WriteHeader(1,"第一列"); Excel_example.WriteHeader(2,"第二列"); //添加核心数据 Excel_example.WriteData(1,1,"数据1"); Excel_example.WriteData(1,2,"数据2"); //保存文件 Excel_example.Save(); //关闭文件 Excel_example.Close(); } 7、注意事项 1)一般单个Excel文件包含多个sheet,程序默认打开第一个; 2)指定操作sheet,使用Excel_example.SetSheet(2)函数; 3)打开文件时最左侧的sheet序号为1,新建excel时最新添加的sheet序号为1. 【后记】 本程序主要基于网络CSDN中---“Excel封装库V2.0”---完成,下载地址是:http://download.csdn.net/detail/yeah2000/3576494,在此表示感谢!同时, 1)在其基础上作了小改动,改正了几个小错误,添加了几个小接口; 2)添加了如何使用的例子,原程序是没有的; 3)详细的注释 发现不足之处,还请大家多多指教!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值