#include "excelinport.h"
#include "DebugUtil.h"
#include "MessageException.h"
#include "charcode.h"

#include <QMessageBox>

ExcelInport::ExcelInport(QObject *parent)
	: QObject(parent)
	, excel(nullptr)
	, workbook(nullptr)
	, currentWorkSheet(nullptr)
	, startRow(-1)
	, startColumn(-1)
{
}

void ExcelInport::openExcel(const QString &filename)
{
	excel = new QAxObject("Excel.Application", this);
    if(excel == nullptr)
		throw MessageException("请安装office");

    excel->dynamicCall("SetVisible(bool)",false);
	QAxObject *workbooks = excel->querySubObject("Workbooks");
	if (!workbooks)
		throw MessageException("Excel打开失败");
	workbook = workbooks->querySubObject("Open(QString,QVariant,QVariant)", filename, 3, true);
	if (!workbook)
		throw MessageException("Excel打开失败");
	currentWorkSheet = workbook->querySubObject("WorkSheets(int)", 1);
	if (!currentWorkSheet)
		throw MessageException("打开Excel工作薄失败");
	QAxObject *usedrange = currentWorkSheet->querySubObject("UsedRange");
	startRow = usedrange->property("Row").toInt();
	startColumn = usedrange->property("Column").toInt();
}

QAxObject *ExcelInport::getCurrentUserRange()
{
	return currentWorkSheet->querySubObject("UsedRange");
}


int ExcelInport::getRows()
{
	QAxObject *rowObj = getCurrentUserRange()->querySubObject("Rows");
	return rowObj->property("Count").toInt();
}

int ExcelInport::getColumns()
{
	QAxObject *columnObj = getCurrentUserRange()->querySubObject("Columns");
	return columnObj->property("Count").toInt();
}

QVariant ExcelInport::getValue(int row, int column)
{
	QAxObject *cell = currentWorkSheet->querySubObject("Cells(int,int)", row + startRow, column + startColumn );
	if (cell)
		return cell->property("Value");
	return QVariant();
}

void ExcelInport::closeExcel()
{
	if (workbook != nullptr)
	{
		workbook->dynamicCall("Close(Boolean)", false);
		workbook = nullptr;
	}

	if (excel != nullptr)
	{
		excel->dynamicCall("Quit()");
		delete excel;
		excel = nullptr;
		currentWorkSheet = nullptr;
		startRow = -1;
		startColumn = -1;
	}
}



