#include <QDebug>
#include <QAxObject>
#include <QStandardPaths>
#include <QFileDialog>
#include <QVariant>
#include <QCoreApplication>
QAxObject *pApplication = NULL;
QAxObject *pWorkBooks = NULL;
QAxObject *pWorkBook = NULL;
QAxObject *pSheets = NULL;
QAxObject *pSheet = NULL;
ExcelImfo excel;
//初始化相关指针
void ExcelImfo::initExcelConfig()
{
pApplication = new QAxObject;
pWorkBooks = new QAxObject;
pWorkBook = new QAxObject;
pSheets = new QAxObject;
pSheet = new QAxObject;
}
//新建excel
void ExcelImfo::newExcel(QString &fileName)
{
pApplication->setControl("Excel.Application");
pApplication->setProperty("Visible", false); //不显示任何警告信息
pApplication->dynamicCall("SetVisible(bool)",false); //不显示窗体
pWorkBooks = pApplication->querySubObject("WorkBooks"); //获取工作簿集合
QFile file(fileName);
if(!file.exists())
{
pWorkBooks->dynamicCall("Add");
pWorkBook = pApplication->querySubObject("ActiveWorkBook");
#ifdef EXCEL_WORK_DEBUG
qDebug()<<"创建新文件"<<"printerData.xls";
#endif
}
else
{
pWorkBook = pWorkBooks->querySubObject("Open(const QString &)", fileName);
#ifdef EXCEL_WORK_DEBUG
qDebug()<<"打开文件"<<"printerData.xls";
#endif
}
pSheets = pWorkBook->querySubObject("Sheets");
pSheet = pSheets->querySubObject("Item(int)", 1);
}
//2.增加1个Worksheet
void ExcelImfo::appendSheet(const QString &sheetName,int cnt)
{
QAxObject *pLastSheet = pSheets->querySubObject("Item(int)", cnt);
pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
pSheet = pSheets->querySubObject("Item(int)", cnt);
pLastSheet->dynamicCall("Move(QVariant)", pSheet->asVariant());
pSheet->setProperty("Name", sheetName);
}
//3.向Excel单元格中写入数据
void ExcelImfo::setCellValue(int row, int column, const QString &value)
{
QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column);
pRange->dynamicCall("Value", value);
}
//5.保存Excel
void ExcelImfo::saveExcel(const QString &fileName)
{
pWorkBook->dynamicCall("SaveAs(const QString &)",
QDir::toNativeSeparators(fileName));
}
//6.释放Excel
void ExcelImfo::freeExcel()
{
if (pApplication != NULL)
{
pApplication->dynamicCall("Quit()");
delete pApplication;
pApplication = NULL;
}
}