赞
踩
QT += axcontainer
#include <QAxObject>
- void newExcel(const QString &fileName);// 新建一个excel
- void appendSheet(const QString &sheetName,int cnt);// 增加一个worksheet
- void setCellValue(int row,int column,const QString &value);// 向Excel单元格中写入数据
- void saveExcel(const QString &fileName);// 保存excel
- void freeExcel();// 释放excel
-
- private:
- Ui::TestExcel *ui;
- QAxObject *pApplication;
- QAxObject *pWorkBooks;
- QAxObject *pWorkBook;
- QAxObject *pSheets;
- QAxObject *pSheet;
- // 新建一个excel
- void TestExcel::newExcel(const QString &fileName)
- {
- pApplication = new QAxObject("Excel.Application");
- if (pApplication == nullptr) {
- 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);
- }
-
- // 增加一个worksheet
- void TestExcel::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);
- }
-
- // 向Excel单元格中写入数据
- void TestExcel::setCellValue(int row,int column,const QString &value)
- {
- QAxObject *pRange = pSheet->querySubObject("Cells(int,int)",row,column);
- pRange->dynamicCall("Value",value);
- }
-
- // 保存excel
- void TestExcel::saveExcel(const QString &fileName)
- {
- pWorkBook->dynamicCall("SaveAs(const QString &)",QDir::toNativeSeparators(fileName));
- }
-
- // 释放excel
- void TestExcel::freeExcel()
- {
- if (pApplication != nullptr) {
- pApplication->dynamicCall("Quit()");
- delete pApplication;
- pApplication = nullptr;
- }
- }
- void TestExcel::on_writeBtn_2_clicked()
- {
- QString fileName = "e:/测试.xlsx";
- newExcel(fileName);
- setCellValue(3,3,"Hello");
- setCellValue(3,6,"World");
- saveExcel(fileName);
- freeExcel();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。