QT 读Excel表格

#ifndef UICOMMONMODULE_AXEXCELFUNCTION_H
#define UICOMMONMODULE_AXEXCELFUNCTION_H

#include "UI/ComDefined.h"
#include 
#include 

class QAxObject;
namespace UICommonMdl
{
	typedef enum
	{
		AX_EXCEL_NULL = 0,		//EXCEL未存在
		AX_EXCEL_BEFORE_2003,	//2003以前的版本,包括2003
		AX_EXCEL_AFTER_2003,	//2003以后的版本
	}AxExcelVersion_e;//excel 版本信息

	class AxExcelCellProperty;
	//通过QAxObject 操作excel的类
	class UICOMMONMODEL_EXPORT AxExcelFunction : public QObject
	{
		Q_OBJECT

	public:
		AxExcelFunction(QObject *parent = 0);
		~AxExcelFunction();
		///获取错误信息
		QString GetErrorMsg() ; 
		//是否产生了错误
		bool IsHasError();
		//判断EXCEL版本  (返回AxExcelVersion_e)
		static AxExcelVersion_e CheckExcelVersion();
		//根据EXCEL版本返回支持的文件类型
		static QString GetExcelFileFilter(bool bIsSupportCsvANDPdf = false);

		///打开或者新建指定的excel文件
		bool OpenExcel(const QString &strFileName, const bool bNew = false) ; 
		//设置工作表名称
		bool SetSheetName(const QString &strSheetName);
		//从iRow行iColumn列开始设置多个单元格内容值。每个格式一个QString值
		bool SetMultiCellValue(int iFromRow, int iFromColumn,const QList> &listValue);
		//合并单元格并设置单元格式值
		bool SetMergeCellValue( int iFromRow, int iFromColumn,int iToRow, int iToColumn,const QString &strValue );

		//开始增加内存值 从开始增加到结束增加EndAddMemoryAndSave,每一行的列数都是iColumnCount
		void BeginAddMemory(const int iColumnCount,const int iBeginRow,const int iBeginColumn);
		//增加单元格内容值
		bool AddCellValue(const QString &strValue);
		//增加不要自动转换的单元格内容值 前面加单引号,防止excel自动将日期 时间 数字转换成不认识的形式
		bool AddNoAutoTranCellValue(const QString &strValue);
		//结束增加内存值并保存到excel文件
		bool EndAddMemoryAndSave();

		//保存excel
		void SaveExcel();
		///释放Excel资源
		void FreeExcel() ;

		//多少行
		int GetRowCout();
		//多少列
		int GetColumnCout();

		//读取一行值 从1开始
		void GetRowValue( int iRow, QStringList &listColumnValues );
		//读取单元格内的值 列和行都从1开始
		QString GetCellValue( int iRow, int iColumn );
		//读取单元格内的值 列和行都从1开始
		QVariant GetCellVariantValue( int iRow, int iColumn );

        //设置标题的样式
		bool SetExcelTitleProperty();
		//设置字段头的样式
		bool SetCellHeaderProperty();
		//设置字段内容的样式
		bool SetCellContextProperty();
		//设置行高
		bool SetCellRowHeight(const int iRowHight);
		//设置列宽
		bool SetColumnWidth(const int iColumnWidth); 
		//设置背景色
		bool SetBackgroudColor(const QColor val);
		//边框色
		bool SetBordersColor(const QColor val); 
		//字体颜色
		bool SetFontColor(const QColor val);
		//字体是否带下划线
		bool SetFontUnderline(const bool val); 
		//是否倾斜
		bool SetFontItalic(const bool val); 
		//是否加粗
		bool SetFontBold(const bool val);
		//字体大小
		bool SetFontSize(const int val);
		//字体名称
		bool SetFontName(const QString val);

		typedef enum
		{  
			EXCEL_HORIZONTAL_ALIGNMENT_LEFT,						//左对齐
			EXCEL_HORIZONTAL_ALIGNMENT_CENTER,						//居中
			EXCEL_HORIZONTAL_ALIGNMENT_RIGHT,						//右对齐
		}ExcelHorizontalAlignment_e;//excel内容左右对齐方式
		//设置上下对齐方式
		bool SetCellHorizontalAlignment(const ExcelHorizontalAlignment_e emAlignment);

		typedef enum
		{  
			EXCEL_VERTICAL_ALIGNMENT_TOP,						//上对齐
			EXCEL_VERTICAL_ALIGNMENT_CENTER,					//居中
			EXCEL_VERTICAL_ALIGNMENT_BOTTOM,					//下对齐
		}ExcelVerticalAlignment_e;//excel内容左右对齐方式
		//设置上下对齐方式
		bool SetCellVerticalAlignment(const ExcelVerticalAlignment_e emAlignment); 
	protected:
		//读取sheet
		bool ReadSheets();

		//读取所有内容
		QVariant ReadAll(); 

		//把列数转换为excel的字母序号
		void convertToColName(int data,QString &res);
		//
		QString to26AlphatString(int data);
		
		//二维数据转换为一维数据
		void castListListVar2Var(QVariant &res,QList > &cells);

		//一维数据转换为二维数据
		void castVar2ListListVar(QVariant &res,QList > &cells); 

    private:
		//是否打开了excel
		bool IsOpenExcel();
	private:
		typedef enum
		{ 
			EXCEL_READ_OPERATE_ERRORCODE_NONE,								//无错误
			EXCEL_READ_OPERATE_ERRORCODE_UNINSTALL,							//未安装excel
			EXCEL_READ_OPERATE_ERRORCODE_OPEN_FAILURE,						//打开excel失败
			EXCEL_READ_OPERATE_ERRORCODE_NO_EXISTS,							//excel文件不存在
			EXCEL_READ_OPERATE_ERRORCODE_HEADER_ERROR,						//表头格式错误
		}ExcelReadOperateErrorCode_e;//excel读取操作错误码

		ExcelReadOperateErrorCode_e						m_emErrorCode;		//错误码

		QAxObject*										m_pExcel;			//excel程序
		QAxObject*										m_pExcelBooks;		//打开的excel文件
		QAxObject*										m_pExcelBook;		//当前打开的excel文件
		QAxObject*										m_pExcelWorksheets;	//当前打开的excel文件的所有工作簿
		QAxObject*										m_pExcelWorksheet;	//当前打开的excel工作簿
		AxExcelVersion_e								m_emExcelVersion;	//Excel版本信息
		bool											m_bNewExcelFile;	//是否是新建excel

        QString											m_strFileName;		//excel 文件名

		int												m_iSheetsCount;		//多少工作表
		int												m_iRowStart;		//开始行数	
		int												m_iColStart;		//开始列数	
		int												m_iCols;			//多少列	
		int												m_iRows ;			//多少行
		
		AxExcelCellProperty*							m_pCellProperty;	//单元格属性
		
		QList >*						m_pCellValues;		//单元格值
		
		QList>*							m_pAddMemoryValue;	//要增加的值
		int												m_iMemoryColCount;//缓存到内存的一行的列数	
		int												m_iMemoryBeginCol;//缓存到内存的开始列号	
		int												m_iMemoryBeginRow;//缓存到内存的开始行号	
	 
	};

	//excel的属性
	class AxExcelCellProperty
	{
	public:
		AxExcelCellProperty();
		~AxExcelCellProperty();

        //设置单元格的属性
		void SetCellProperty(QAxObject *pCell);
		//恢复默认单元格的属性
		void ReSetCellProperty();

		int RowHight() const { return m_iRowHight; }
		void RowHight(int val) { m_iRowHight = val; }
		int ColumnWidth() const { return m_iColumnWidth; }
		void ColumnWidth(int val) { m_iColumnWidth = val; }
		int HAlignment() const { return m_iHAlignment; }
		void HAlignment(int val) { m_iHAlignment = val; }
		int VAlignment() const { return m_iVAlignment; }
		void VAlignment(int val) { m_iVAlignment = val; }
		QColor BackgroudColor() const { return m_BackgroudColor; }
		void BackgroudColor(const QColor &val) { m_BackgroudColor = val; }
		QColor BordersColor() const { return m_BordersColor; }
		void BordersColor(const QColor& val) { m_BordersColor = val; }
		QColor FontColor() const { return m_FontColor; }
		void FontColor(const QColor &val) { m_FontColor = val; }
		bool FontUnderline() const { return m_bFontUnderline; }
		void FontUnderline(bool val) { m_bFontUnderline = val; }
		bool FontItalic() const { return m_bFontItalic; }
		void FontItalic(bool val) { m_bFontItalic = val; }
		bool FontBold() const { return m_bFontBold; }
		void FontBold(bool val) { m_bFontBold = val; }
		int FontSize() const { return m_iFontSize; }
		void FontSize(int val) { m_iFontSize = val; }
		QString FontName() const { return m_strFontName; }
		void FontName(const QString &val) { m_strFontName = val; }

    private:
		int												m_iRowHight;		//行高
		int												m_iColumnWidth;		//列宽	
		int												m_iHAlignment;		//左右对齐方式
		int												m_iVAlignment;		//上下对齐方式	

		QColor											m_BackgroudColor ;	//背景色
		QColor											m_BordersColor ;	//边框色
		QColor											m_FontColor ;		//字体色


		QString											m_strFontName ;		//字体名
		int												m_iFontSize;		//字体大小
		bool											m_bFontBold;		//字体是否加粗
		bool											m_bFontItalic;		//字体是否倾斜
		bool											m_bFontUnderline;	//字体是否加下划线
	};
}
#endif // TRANSTOOL_AxExcelFunction_H
#include "stdafx.h"
#include "AxExcelFunction.h"
#include 
#include 
#include 
#include 
#include 
#include  
#include 
 
#define EXCEL_AFTER_2003_POSTIFX_NAME	"xlsx"   //2003 版本后的excel默认后缀名
#define EXCEL_BEFORE_2003_POSTIFX_NAME	"xls"	 //2003 版本前的excel后缀名
#define EXCEL_CSV_POSTIFX_NAME	"csv"   // csv
#define EXCEL_PDF_POSTIFX_NAME	"pdf"   // pdf

#define Q_DELETE(T)  if(T != NULL) {  delete T; T = NULL;}

namespace UICommonMdl
{
	AxExcelFunction::AxExcelFunction(QObject *parent)
	: QObject(parent),
	m_emErrorCode(EXCEL_READ_OPERATE_ERRORCODE_NONE),
	m_pExcel(NULL),
	m_pExcelBooks(NULL),
	m_pExcelBook(NULL),
	m_pExcelWorksheets(NULL),
	m_pExcelWorksheet(NULL),
	m_pCellProperty(NULL),
	m_pCellValues(NULL),
	m_pAddMemoryValue(NULL),
	m_iMemoryColCount(0),
	m_iMemoryBeginCol(0),
	m_iMemoryBeginRow(0),
	m_emExcelVersion(AX_EXCEL_NULL),
	m_bNewExcelFile(false),
	m_iSheetsCount(0),
	m_iRowStart(0),
	m_iColStart(0),
	m_iCols(0),
	m_iRows(0)
	{
		m_pCellProperty = new AxExcelCellProperty();	
		m_pCellValues = new QList >;
		m_pAddMemoryValue = new QList>;
	}

	AxExcelFunction::~AxExcelFunction()
	{
		Q_DELETE(m_pCellProperty);
		Q_DELETE(m_pCellValues);
		Q_DELETE(m_pAddMemoryValue);
		FreeExcel();	
	} 

	void AxExcelFunction::convertToColName( int data,QString &res )
	{
		Q_ASSERT(data >0 && data <65535);
		int tempData = data / 26;
		if (tempData > 0)
		{
			int mode = data%26;
			convertToColName(mode,res);
			convertToColName(tempData,res);

		}
		else
		{
			res = (to26AlphatString(data) + res);
		}

	}

	QString AxExcelFunction::to26AlphatString( int data )
	{
		QChar ch = data + 0x40;
		return QString(ch);

	}

	void AxExcelFunction::castListListVar2Var(QVariant &res,QList > &cells )
	{
		QVariantList vars;
		int rows = cells.size();
		for (int i = 0; i < rows; i++)
		{
			vars.append(QVariant(cells[i]));
		}
		res = QVariant(vars);

	}

	QVariant AxExcelFunction::ReadAll()
	{
		QVariant varRange;
		try
		{
			if (!m_pExcelWorksheet->isNull()&& NULL != m_pExcelWorksheet)
			{
				QAxObject *pRange = m_pExcelWorksheet->querySubObject("UsedRange");

				if (pRange->isNull() || NULL == pRange)
				{ 
					return -1;
				}
				varRange = pRange->dynamicCall("Value"); 
				Q_DELETE(pRange);
			}
		}
		catch(...)
		{
		}
		return varRange;
	}

	void AxExcelFunction::GetRowValue( int iRow, QStringList &listColumnValues )
	{
		iRow--; 
		listColumnValues.clear();
		if (iRow > m_iRows || iRow < 0)
		{
			return;
		}
		if (0 == m_pCellValues->at(iRow).size())
		{
			return;
		}

		int iColumns =  m_pCellValues->at(iRow).size();
		for(int iColumn = 0; iColumn < iColumns; ++iColumn)
		{
			QVariant var = m_pCellValues->at(iRow).at(iColumn);

			if (!var.isValid() || var.isNull())
			{
				listColumnValues.append("");
			}
			else
			{
				listColumnValues.append(var.toString());
			}
		} 
	}

	QString AxExcelFunction::GetCellValue( int iRow, int iColumn ) 
	{ 
		return GetCellVariantValue(iRow, iColumn).toString().trimmed();
	}

	QVariant AxExcelFunction::GetCellVariantValue( int iRow, int iColumn )
	{
		iRow--;
		iColumn--;
		if (iRow > m_iRows || iRow < 0 || iColumn > m_iCols || iColumn < 0)
		{
			return "";
		}
		if (m_pCellValues->at(iRow).size() < iColumn)
		{
			return "";
		}
		return m_pCellValues->at(iRow).at(iColumn);
	}

	void AxExcelFunction::castVar2ListListVar( QVariant &res,QList > &cells )
	{
		cells.clear();
		QVariantList varRow = res.toList();
		if (varRow.isEmpty())
		{
			return;
		}
		int iRows = varRow.size();
		QVariantList varData;
		for (int i = 0; i < iRows; i++)
		{
			varData = varRow[i].toList();
			cells.push_back(varData);
		}
		
	}

	bool AxExcelFunction::ReadSheets()
	{
		m_pCellValues->clear();
		m_iRows = 0;
		m_iCols = 0;
		castVar2ListListVar(ReadAll(),*m_pCellValues);
		if (m_pCellValues->size() <= 1)
		{
			return false;
		}

		int iColumns = 0;
		int iRows =  m_pCellValues->size();
		for(int iRow = 0; iRow < iRows; ++iRow)
		{
			int iColumn = m_pCellValues->at(iRow).size();
			iColumns = qMax(iColumns, iColumn); 
		}
		m_iRows = iRows;
		m_iCols = iColumns;
		return true;
	}

	bool AxExcelFunction::OpenExcel( const QString &strFileName , const bool bNew)
	{
		if (strFileName.isNull() || strFileName.isEmpty())
		{
			m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_NO_EXISTS;
			return false;
		}
		m_bNewExcelFile = bNew;
		if (bNew)
		{
			if(QFile::exists(strFileName))
			{
				QFile::remove(strFileName);
				if(QFile::exists(strFileName))
				{ 
					m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_OPEN_FAILURE;
					return false;
				}
			}
		} 
		else
		{
			QFile file(strFileName);   
			if (!file.exists())	
			{
				m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_NO_EXISTS;
				return false;
			}
		}
		FreeExcel(); 
		m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_NONE; 
		//监测下excel版本
		m_emExcelVersion = CheckExcelVersion();
		//没装excel 退出返回失败
		if (AX_EXCEL_NULL == m_emExcelVersion)
		{
			m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_UNINSTALL; 
			return false;
		}
		//默认下 打开excel失败
		m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_OPEN_FAILURE; 
		m_pExcel = new QAxObject("Excel.Application");
		if (!m_pExcel || m_pExcel->isNull())
		{
			if (m_pExcel)
			{
				m_pExcel->dynamicCall("Quit(void)");
				Q_DELETE(m_pExcel); 
			}
			return false;
		}  
		m_pExcel->dynamicCall("SetVisible(bool)", false);
		m_pExcel->setProperty("DisplayAlerts", false);//不显示任何警告信息。 
		m_pExcelBooks = m_pExcel->querySubObject("WorkBooks");  
		if (!m_pExcelBooks || m_pExcelBooks->isNull())
{
			m_pExcel->dynamicCall("Quit(void)");
			Q_DELETE(m_pExcel); 
			return false;
		}
		if (bNew)
		{
			m_pExcelBooks->dynamicCall("Add");
			m_pExcelBook = m_pExcel->querySubObject("ActiveWorkBook");   
		}
		else
		{
			m_pExcelBook = m_pExcelBooks->querySubObject("Open(const QString &)", QDir::toNativeSeparators(strFileName) ); 
		}

if (!m_pExcelBook || m_pExcelBook->isNull())
		{
			m_pExcel->dynamicCall("Quit(void)");
			Q_DELETE(m_pExcel); 
			return false;
		}
		m_pExcelWorksheets = m_pExcelBook->querySubObject("Sheets"); //Sheets也可换用WorkSheets
		m_iSheetsCount = m_pExcelWorksheets->property("Count").toInt(); //获取工作表数目
		
		if (m_iSheetsCount > 0)
		{
			m_pExcelWorksheet = m_pExcelBook->querySubObject("WorkSheets(int)", 1);//打开第一个sheet  
		}
		if (!m_pExcelWorksheet|| m_pExcelWorksheet->isNull())
		{
			m_pExcelBook->dynamicCall("Close (Boolean)", false);
			m_pExcel->dynamicCall("Quit(void)");
			Q_DELETE(m_pExcel); 
			return false;
		} 
		if (!bNew)
		{
			ReadSheets();
		}
		m_strFileName = strFileName;
		m_emErrorCode = EXCEL_READ_OPERATE_ERRORCODE_NONE;
		return true;
	}

	bool AxExcelFunction::IsHasError()
	{
		return (m_emErrorCode != EXCEL_READ_OPERATE_ERRORCODE_NONE);
	}

	QString AxExcelFunction::GetErrorMsg()
	{
		QString strErrorMsg;
		strErrorMsg.clear();
		switch (m_emErrorCode)
		{
		case EXCEL_READ_OPERATE_ERRORCODE_UNINSTALL:
			strErrorMsg = tr("The excel application is not found.");
			break;
		case EXCEL_READ_OPERATE_ERRORCODE_OPEN_FAILURE:
			strErrorMsg = tr("Open excel file failed.");
			break;
		case EXCEL_READ_OPERATE_ERRORCODE_NO_EXISTS:
			strErrorMsg = tr("Excel file non-existent.");
			break;
		case EXCEL_READ_OPERATE_ERRORCODE_HEADER_ERROR:
			strErrorMsg = tr("The column header of the import file is incorrect!");
			break; 
		}
		return strErrorMsg;
	}

	void AxExcelFunction::SaveExcel()
	{
		if (m_pExcel && m_pExcelBook)  
		{
			//是新建文件夹 要保存了
			if (m_bNewExcelFile)
			{
				QString strFileAffix;
				int iPos = m_strFileName.lastIndexOf(".");
				if (iPos > 0)
				{
					strFileAffix = m_strFileName.right(m_strFileName.length() - iPos - 1);
				}
				switch (m_emExcelVersion)
				{
				case AX_EXCEL_BEFORE_2003:
					{
						//后缀名为空的话,加上默认后缀名
						if (strFileAffix.isEmpty())
						{
							m_strFileName.append(".");
							m_strFileName.append(EXCEL_BEFORE_2003_POSTIFX_NAME);
						}
						//后缀名不等于默认值的话,2003之前版本要改过来
						else if (strFileAffix.toLower() != EXCEL_BEFORE_2003_POSTIFX_NAME)
						{
							m_strFileName = m_strFileName.left(iPos) + EXCEL_BEFORE_2003_POSTIFX_NAME;
						}
						m_pExcelBook->dynamicCall("SaveAs(const QString &)",  
							QDir::toNativeSeparators(m_strFileName));

					}
					break;
				case AX_EXCEL_AFTER_2003:
					{
						//后缀名为空的话,加上默认后缀名
						if (strFileAffix.isEmpty())
						{
							m_strFileName.append(".");
							m_strFileName.append(EXCEL_AFTER_2003_POSTIFX_NAME);
							m_pExcelBook->dynamicCall("SaveAs(const QString &)",  
								QDir::toNativeSeparators(m_strFileName));
						} 
						else if (strFileAffix.toLower() == EXCEL_AFTER_2003_POSTIFX_NAME)
						{
							m_pExcelBook->dynamicCall("SaveAs(const QString &)",  
								QDir::toNativeSeparators(m_strFileName));
						}
						else if (strFileAffix.toLower() == EXCEL_CSV_POSTIFX_NAME)
						{
							m_pExcelBook->dynamicCall("SaveAs(const QString &, int)",  
								QDir::toNativeSeparators(m_strFileName),6);
						}
						else if (strFileAffix.toLower() == EXCEL_PDF_POSTIFX_NAME)
						{
							m_pExcelBook->dynamicCall("ExportAsFixedFormat(int, const QString &)",  
								0,QDir::toNativeSeparators(m_strFileName));
						}						
						else
						{
							m_pExcelBook->dynamicCall("SaveAs(const QString &, int)",  
								QDir::toNativeSeparators(m_strFileName),56);

						}
					}
					break;
				}
			}
		}
	}

	void AxExcelFunction::FreeExcel()
	{
		if (m_pExcel)  
		{
			if (m_pExcelBook)
			{
				m_pExcelBook->dynamicCall("Close (Boolean)", false);
			}
			m_pExcel->dynamicCall("Quit()");  
			Q_DELETE(m_pExcel); 
		} 
		m_pExcelBooks = NULL;
		m_pExcelBook = NULL;
		m_pExcelWorksheet = NULL;
		m_iSheetsCount = 0;
		m_iRowStart = 0;
		m_iColStart = 0;
		m_iCols = 0;
		m_iRows = 0;
	}

	//excel 是否打开
	bool AxExcelFunction::IsOpenExcel()
	{
		return (NULL != m_pExcelWorksheet);
	}

	bool AxExcelFunction::SetSheetName( const QString &strSheetName )
	{ 
		if (!IsOpenExcel())
		{
			return false;
		} 
		m_pExcelWorksheet->setProperty("Name", strSheetName); //设置工作表名称
		return true;
	}

	bool AxExcelFunction::SetMultiCellValue( int iFromRow, int iFromColumn,const QList> &listValue )
	{
		if (!IsOpenExcel())
		{
			return false;
		} 
		if(listValue.isEmpty() || listValue[0].isEmpty())
		{
			return false;
		}
		QString strRange;
		//行列转换,转换
		QList > lstTmp;
		for(int i = 0; i < listValue.size(); ++i)
		{
			lstTmp.append(QList());
			for(int j = 0; j < listValue[i].size();++j)
			{
				lstTmp.back().append(listValue[i][j]);
			}
		}
		int col = lstTmp.at(0).size();
		int row = lstTmp.size();

        QString strFromRange;
		convertToColName(iFromColumn,strFromRange);
		strFromRange += QString::number(iFromRow);

		convertToColName(col,strRange);
		strRange += QString::number(row + iFromRow - 1);
		strRange = strFromRange +  ":" + strRange;
		qDebug()<querySubObject("Range(const QString&)",strRange);
		if (NULL == pRange || pRange->isNull())
		{
			return false;
		} 
		QVariant var;
		castListListVar2Var(var,lstTmp);
		pRange->dynamicCall("SetValue(const QVariant&)",var); 
		pRange->setProperty("NumberFormatLocal","@");
		//pRange->setProperty("NumberFormatLocal", "yyyy/m/d");//设置单元格的日期
		m_pCellProperty->SetCellProperty(pRange);
		Q_DELETE(pRange);
		return true;
	}

	bool AxExcelFunction::SetMergeCellValue( int iFromRow, int iFromColumn,int iToRow, int iToColumn,const QString &strValue )
	{
		if (!IsOpenExcel())
		{
			return false;
		} 
		QString strFromRange;
		convertToColName(iFromColumn,strFromRange);
		strFromRange += QString::number(iFromRow);

		QString strToRange;
		convertToColName(iToColumn,strToRange);
		strToRange += QString::number(iToRow);
		//设置单元格内容
		QAxObject *pCellValue = m_pExcelWorksheet->querySubObject("Range(const QString&)", strFromRange);
		if (pCellValue && !pCellValue->isNull())
		{
			QVariant var = QVariant(strValue);
			pCellValue->dynamicCall("SetValue(const QVariant&)",var); //设置单元格值 
			Q_DELETE(pCellValue);
		}
		else
		{
			return false;
		}
		QString merge_cell;
		merge_cell.append(strFromRange); //初始列 
		merge_cell.append(":");
		merge_cell.append(strToRange); //终止列 
		QAxObject *pMergeRange = m_pExcelWorksheet->querySubObject("Range(const QString&)", merge_cell);	

		if (pMergeRange && !pMergeRange->isNull())
		{
			m_pCellProperty->SetCellProperty(pMergeRange); 
			pMergeRange->setProperty("MergeCells", true); //合并单元格 
			Q_DELETE(pMergeRange);
			return true;
		}
		else
		{
			return false;
		} 
	}

	bool AxExcelFunction::SetCellRowHeight( const int iRowHight )
	{
		m_pCellProperty->RowHight(iRowHight);
		return true;
	}

	bool AxExcelFunction::SetColumnWidth( const int iColumnWidth )
	{
		m_pCellProperty->ColumnWidth(iColumnWidth);
		return true;
	}

	bool AxExcelFunction::SetBackgroudColor( const QColor val )
	{
		m_pCellProperty->BackgroudColor(val);
		return true;
	}

	bool AxExcelFunction::SetBordersColor( const QColor val )
	{
		m_pCellProperty->BordersColor(val);
		return true;
	}

	bool AxExcelFunction::SetFontColor( const QColor val )
	{
		m_pCellProperty->FontColor(val);
		return true;
	}

	bool AxExcelFunction::SetFontUnderline( const bool val )
	{
		m_pCellProperty->FontUnderline(val);
		return true;
	}

	bool AxExcelFunction::SetFontItalic( const bool val )
	{
		m_pCellProperty->FontItalic(val);
		return true;
	}

	bool AxExcelFunction::SetFontBold( const bool val )
	{
		m_pCellProperty->FontBold(val);
		return true;
	}

	bool AxExcelFunction::SetFontSize( const int val )
	{
		m_pCellProperty->FontSize(val);
		return true;
	}

	bool AxExcelFunction::SetFontName( const QString val )
	{
		m_pCellProperty->FontName(val);
		return true;
	}

	bool AxExcelFunction::SetCellHorizontalAlignment( const ExcelHorizontalAlignment_e emAlignment )
	{
		int iAlignmentValue  = -4108;
		//左对齐(xlLeft):-4131 居中(xlCenter):-4108 右对齐(xlRight):-4152
		switch (emAlignment)
		{
		case EXCEL_HORIZONTAL_ALIGNMENT_LEFT:
			iAlignmentValue  = -4131;
			break;
		case EXCEL_HORIZONTAL_ALIGNMENT_CENTER:
			iAlignmentValue  = -4108;
			break;
		case EXCEL_HORIZONTAL_ALIGNMENT_RIGHT:
			iAlignmentValue  = -4152;
			break;
		default:
			return false;
		}
		m_pCellProperty->HAlignment(iAlignmentValue);
		return true;

	}

	bool AxExcelFunction::SetCellVerticalAlignment( const ExcelVerticalAlignment_e emAlignment )
	{
		int iAlignmentValue  = -4108;
		//上对齐(xlTop)-4160 居中(xlCenter):-4108 下对齐(xlBottom):-4107
		switch (emAlignment)
		{
		case EXCEL_VERTICAL_ALIGNMENT_TOP:
			iAlignmentValue  = -4160;
			break;
		case EXCEL_VERTICAL_ALIGNMENT_CENTER:
			iAlignmentValue  = -4108;
			break;
		case EXCEL_VERTICAL_ALIGNMENT_BOTTOM:
			iAlignmentValue  = -4107;
			break;
		default:
			return false;
		}
		m_pCellProperty->VAlignment(iAlignmentValue);
		return true;
	}

	bool AxExcelFunction::SetExcelTitleProperty()
	{
		m_pCellProperty->ReSetCellProperty();
		SetBackgroudColor(QColor(51,51,153));
		SetBordersColor(QColor(0,0,0));
		SetFontColor(QColor(255,255,255));
		SetFontSize(16);
		SetCellRowHeight(30);
		return true; 
	}

	bool AxExcelFunction::SetCellHeaderProperty()
	{
		m_pCellProperty->ReSetCellProperty();
		SetBackgroudColor(QColor(255,255,255));
		SetBordersColor(QColor(0,0,0));
		SetFontColor(QColor(0,0,0));
		SetFontSize(9);
		SetFontBold(true);
		SetCellRowHeight(20); 
		return true;
	}

	bool AxExcelFunction::SetCellContextProperty()
	{
		m_pCellProperty->ReSetCellProperty();
		SetBackgroudColor(QColor(243,245,184));
		SetBordersColor(QColor(0,0,0));
		SetFontColor(QColor(0,0,0));
		SetFontSize(9);
		SetCellRowHeight(20); 
		return true;
	}

	void AxExcelFunction::BeginAddMemory(const int iColumnCount,const int iBeginRow,const int iBeginColumn)
	{
		m_pAddMemoryValue->clear();
		m_iMemoryColCount = iColumnCount;
		m_iMemoryBeginCol = iBeginColumn;
		m_iMemoryBeginRow = iBeginRow;
	}

	bool AxExcelFunction::AddCellValue( const QString &strValue )
	{ 
		if (0 == m_pAddMemoryValue->size())
		{
			QList listStr;
			listStr.append(strValue);
			m_pAddMemoryValue->append(listStr);
		}
		else
		{
			int iColumnCount = m_pAddMemoryValue->back().size();
			if (iColumnCount < m_iMemoryColCount)
			{
				m_pAddMemoryValue->back().append(strValue);
			} 
			else
			{
				QList listStr;
				listStr.append(strValue);
				m_pAddMemoryValue->append(listStr); 
			}

		}
		return true;
	}

	bool AxExcelFunction::EndAddMemoryAndSave()
	{
		bool bResult = SetMultiCellValue(m_iMemoryBeginRow, m_iMemoryBeginCol,*m_pAddMemoryValue);  
		m_pAddMemoryValue->clear();
		m_iMemoryColCount = 0;
		m_iMemoryBeginCol = 0;
		m_iMemoryBeginRow = 0;
		return bResult;
	}

	AxExcelVersion_e AxExcelFunction::CheckExcelVersion()
	{
		AxExcelVersion_e emExcelVersion = AX_EXCEL_NULL;
		QAxObject* pExcelApp = new QAxObject("Excel.Application");
		if (NULL == pExcelApp )
		{
			return emExcelVersion;
		}
		if (pExcelApp->isNull())
		{
			pExcelApp->dynamicCall("Quit(void)");
			Q_DELETE(pExcelApp);  
			return emExcelVersion;
		} 
		int iVersion;
		QVariant ver = pExcelApp->property("Version");
		if (ver.isValid())
		{
			iVersion = ver.toString().toFloat(); 
			if (iVersion < 11)
			{
				emExcelVersion = AX_EXCEL_BEFORE_2003;
			} 
			else
			{
				emExcelVersion = AX_EXCEL_AFTER_2003;
			}
		}
		pExcelApp->dynamicCall("Quit(void)");
		Q_DELETE(pExcelApp); 
		return emExcelVersion;
	}

	int AxExcelFunction::GetRowCout()
	{
		return m_iRows;
	}

	int AxExcelFunction::GetColumnCout()
	{
		return m_iCols;
	}

	QString AxExcelFunction::GetExcelFileFilter(bool bIsSupportCsvANDPdf /*= false*/)
	{
		AxExcelVersion_e emExcelVersion = CheckExcelVersion();
		QString strFileFilter;
		switch (emExcelVersion)
		{
		case AX_EXCEL_BEFORE_2003:
			{
				strFileFilter.append(tr("EXCEL files (*.xls)"));
			}
			break;
		case AX_EXCEL_AFTER_2003:
			{
				strFileFilter.append(tr("EXCEL files (*.xlsx)"));
				strFileFilter.append(";;");
				strFileFilter.append(tr("EXCEL files (*.xls)"));

				if (bIsSupportCsvANDPdf)
				{
					strFileFilter.append(";;");
					strFileFilter.append(tr("CSV files (*.csv)"));
					strFileFilter.append(";;");
					strFileFilter.append(tr("PDF files (*.pdf)"));
				}
			}
			break;
		default:
			break;
		}
		return strFileFilter;
	}

	bool AxExcelFunction::AddNoAutoTranCellValue( const QString &strValue )
	{
		return AddCellValue("'" + strValue);
	}

	void AxExcelCellProperty::SetCellProperty( QAxObject *pCell )
	{
		if (!pCell || pCell->isNull())
		{
			return;
		}
		if (m_iRowHight > 0)
		{
			pCell->setProperty("RowHeight", m_iRowHight); //设置单元格行高
		}
		if (m_iColumnWidth > 0)
		{
			pCell->setProperty("ColumnWidth", m_iColumnWidth); //设置单元格列宽
		}
		pCell->setProperty("HorizontalAlignment", m_iHAlignment); //左对齐(xlLeft):-4131 居中(xlCenter):-4108 右对齐(xlRight):-4152
		pCell->setProperty("VerticalAlignment", m_iVAlignment); //上对齐(xlTop)-4160 居中(xlCenter):-4108 下对齐(xlBottom):-4107

		/*QAxObject* pColumns = pCell->querySubObject("Columns");
		if (pColumns&& !pColumns->isNull())
		{
			pColumns->dynamicCall("AutoFit()");//自适应宽度
		} */
		pCell->setProperty("WrapText", true); //内容过多,自动换行
		QAxObject* pInterior = pCell->querySubObject("Interior");
		if (pInterior && !pInterior->isNull())
		{
			//pInterior->setProperty("Color", m_BackgroudColor); //设置单元格背景色
		}
		QAxObject* pBorder = pCell->querySubObject("Borders");
		if (pBorder && !pBorder->isNull())
		{
			pBorder->setProperty("Color", m_BordersColor); //设置单元格边框色
		}
		QAxObject *pFont = pCell->querySubObject("Font"); //获取单元格字体
		if (pFont&& !pFont->isNull())
		{
			if (!m_strFontName.isEmpty())
			{
				pFont->setProperty("Name", m_strFontName); //设置单元格字体
			}
			pFont->setProperty("Bold", m_bFontBold); //设置单元格字体加粗
			if (m_iFontSize > 0)
			{
				pFont->setProperty("Size", m_iFontSize); //设置单元格字体大小
			}
			pFont->setProperty("Italic", m_bFontItalic); //设置单元格字体斜体
			if (m_bFontUnderline)
			{
				pFont->setProperty("Underline", 2); //设置单元格下划线
			} 
			else
			{
				pFont->setProperty("Underline", -4142); //设置单元格下划线
			}
			pFont->setProperty("Color", m_FontColor); //设置单元格字体颜色
		}
	}

	AxExcelCellProperty::AxExcelCellProperty():
	m_iRowHight(0)
	,m_iColumnWidth(18)
	,m_iHAlignment(-4108)
	,m_iVAlignment(-4108)
	,m_BackgroudColor(QColor(243,245,184))
	,m_BordersColor (QColor(0,0,0))
	,m_FontColor(QColor(0,0,0))  
	,m_iFontSize(0)
	,m_bFontBold(false)
	,m_bFontItalic(false)
	,m_bFontUnderline(false)
	{
		m_strFontName.clear();
	}

	AxExcelCellProperty::~AxExcelCellProperty()
	{

	}

	void AxExcelCellProperty::ReSetCellProperty()
	{
		m_iRowHight = 0;
		m_iColumnWidth = 18; 
		m_iHAlignment = -4108;
		m_iVAlignment = -4108; 
		m_BackgroudColor = QColor(243,245,184); 
		m_BordersColor = QColor(0,0,0); 
		m_FontColor = QColor(0,0,0);  
		m_iFontSize = 0; 
		m_bFontBold = false;  
		m_bFontItalic = false;  
		m_bFontUnderline = false;   
		m_strFontName.clear();
	}
}

你可能感兴趣的:(QT,c++)