#include <QFile>
#include <QDir>
#include "exportExcel.h"
ExportExcel::ExportExcel()
{
m_pApplication = NULL;
m_pWorkBooks = NULL;
m_pWorkBook = NULL;
m_pSheets = NULL;
m_pSheet = NULL;
}
ExportExcel::~ExportExcel()
{
}
void ExportExcel::newExcel(const QString &fileName)
{
m_pApplication = new QAxObject();
m_pApplication->setControl("Excel.Application");//连接Excel控件
m_pApplication->dynamicCall("SetVisible(bool)", false);//false不显示窗体
m_pApplication->setProperty("DisplayAlerts", false);//不显示任何警告信息。
m_pWorkBooks = m_pApplication->querySubObject("Workbooks");
QFile file(fileName);
if (file.exists())
{
m_pWorkBook = m_pWorkBooks->querySubObject("Open(const QString &)", fileName);
}
else
{
m_pWorkBooks->dynamicCall("Add");
m_pWorkBook = m_pApplication->querySubObject("ActiveWorkBook");
}
m_pSheets = m_pWorkBook->querySubObject("Sheets");
m_pSheet = m_pSheets->querySubObject("Item(int)", 1);
}
void ExportExcel::appendSheet(const QString &sheetName)
{
int nCount = m_pSheets->property("Count").toInt();
QAxObject *pLastSheet = m_pSheets->querySubObject("Item(int)", nCount);
m_pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
m_pSheet = m_pSheets->querySubObject("Item(int)", nCount);
pLastSheet->dynamicCall("Move(QVariant)", m_pSheet->asVariant());
m_pSheet->setProperty("Name", sheetName);
}
void ExportExcel::setCellValue(int row, int column, const QString &value)
{
QAxObject *pRange = m_pSheet->querySubObject("Cells(int,int)", row, column);
pRange->dynamicCall("Value", value);
}
void ExportExcel::saveExcel(const QString &fileName)
{
m_pWorkBook->dynamicCall("SaveAs(const QString &)",
QDir::toNativeSeparators(fileName));
}
void ExportExcel::freeExcel()
{
if (m_pApplication != NULL)
{
m_pApplication->dynamicCall("Quit()");
delete m_pApplication;
m_pApplication = NULL;
}
}
void ExportExcel::setSheetName(int itemIndex, const QString &sheetName)
{
int nCount = m_pSheets->property("Count").toInt();
if(itemIndex <= nCount)
{
QAxObject *pCurSheet = m_pSheets->querySubObject("Item(int)", itemIndex);
pCurSheet->setProperty("Name", sheetName);
}
}