//基于http://blog.csdn.net/w_ww_w/article/details/9167573的主体
//头文件
#ifndef EXPORTEXCEL_H#define EXPORTEXCEL_H
#include<QAxObject>
#include<QTableView>
#include<QString>
#include<QFile>
#include<QDir>
class ExportExcel
{
public:
ExportExcel(const QString &Path,const QString &Sheetname);
void setCellValue(int row, int column, const QString &value);
void saveExcel();
~ExportExcel();
private:
QAxObject *pApplication;
QAxObject *pWorkBooks;
QAxObject *pWorkBook;
QAxObject *pSheets;
QAxObject *pSheet;
QAxObject *pRange;
QString sheetname;
QString path;
};
#endif // EXPORTEXCEL_H
//定义
#include "Exportexcel.h"
ExportExcel::ExportExcel(const QString &Path,const QString &Sheetname)
{
path=Path;
sheetname=Sheetname;
pApplication = new QAxObject();
pApplication->setControl("Excel.Application");//连接Excel控件
pApplication->dynamicCall("SetVisible(bool)", false);//false不显示窗体
pApplication->setProperty("DisplayAlerts", false);//不显示任何警告信息。
pWorkBooks = pApplication->querySubObject("Workbooks");
QFile file(path);
if (file.exists())
{
pWorkBook = pWorkBooks->querySubObject("Open(const QString &)", path);
}
else
{
pWorkBooks->dynamicCall("Add");
pWorkBook = pApplication->querySubObject("ActiveWorkBook");
}
pSheets = pWorkBook->querySubObject("Sheets");
pSheet = pSheets->querySubObject("Item(int)", 1);
pRange=NULL;
pSheet->dynamicCall("Move(QVariant)", pSheet->asVariant());
pSheet->setProperty("Name", sheetname);
}
//向Excel单元格中写入数据
void ExportExcel::setCellValue(int row, int column, const QString &value)
{
pRange = pSheet->querySubObject("Cells(int,int)", row, column);
pRange->dynamicCall("Value", value);
}
//保存Excel
void ExportExcel::saveExcel()
{
pWorkBook->dynamicCall("SaveAs(const QString &)",
QDir::toNativeSeparators(path));
pWorkBook->dynamicCall("Close()");
pApplication->dynamicCall("Quit()");
}
ExportExcel::~ExportExcel()
{
delete pApplication;
}