正好同事问道Qt下操作excel. 转自:http://blog.csdn.net/a156392343/article/details/48092515
配制方面:
1、确保Excel软件在本地服务器注册成功,没注册成功的可以通过 在运行中"E:\program Files\Microsoft Office\Office12\EXCEL.EXE" /regserver 手动注册,注意路径要用自己的excel路径。
2、确保组件配制正确,运行命令:dcomcnfg,查看DCOM配置下是否有Microsoft Excel Application,有的话万事大吉,开始设置(1)常规,身份验证:无(2)安全、配制权限自定义,控制权限,完全控制选中,保存
以上确保QAxObject可以正常被调用
程序方面:
1、工程pro文件添加
CONFIG += qaxcontainer
2、.h文件添加
/1./打开
void newExcel(const QString &fileName);
//2.增加1个Worksheet
void appendSheet(const QString &sheetName,int cnt);
//3.向Excel单元格中写入数据
void setCellValue(int row, int column, const QString &value);
//4.保存Excel
void saveExcel(const QString &fileName);
//5.释放Excel
void freeExcel();
3、.cpp文件
//1.新建一个excel
void MainWindow::newExcel(const QString &fileName)
{ HRESULT r = OleInitialize(0);
CoInitialize(0);
if (r != S_OK && r != S_FALSE) {
qWarning("Qt: Could not initialize OLE (error %x)\n", (unsigned int)r);
}
pApplication = new QAxObject("Excel.Application");
if(pApplication == NULL){
qWarning("pApplication\n");return;
}
pApplication->dynamicCall("SetVisible(bool)", false);//false不显示窗体
pApplication->setProperty("DisplayAlerts", false);//不显示任何警告信息。
pWorkBooks = pApplication->querySubObject("Workbooks");
QFile file(fileName);
if (file.exists())
{
pWorkBook = pWorkBooks->querySubObject("Open(const QString &)", fileName);
}
else
{
pWorkBooks->dynamicCall("Add");
pWorkBook = pApplication->querySubObject("ActiveWorkBook");
}
pSheets = pWorkBook->querySubObject("Sheets");
pSheet = pSheets->querySubObject("Item(int)", 1);
}
//2.增加1个Worksheet
void MainWindow::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 MainWindow::setCellValue(int row, int column, const QString &value)
{
QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column);
pRange->dynamicCall("Value", value);
}
//4.保存Excel
void MainWindow::saveExcel(const QString &fileName)
{
pWorkBook->dynamicCall("SaveAs(const QString &)",
QDir::toNativeSeparators(fileName));
}
//5.释放Excel
void MainWindow::freeExcel()
{
if (pApplication != NULL)
{
pApplication->dynamicCall("Quit()");
delete pApplication;
pApplication = NULL;
}
}
附上测试的button槽函数
void MainWindow::on_pushButton_keting_clicked()
{
OleInitialize(0);
QString fileNametmp = "d:/112.xls"; //文件名可从此处修改
newExcel(fileNametmp);
// appendSheet("page1");
setCellValue(3, 3,"34343");
setCellValue(3, 6,"55555");
saveExcel(fileNametmp);
freeExcel();
return;
}