当前位置:   article > 正文

Qt 使用QAxObject创建一个excel_qt下新建一个excel文件

qt下新建一个excel文件

1.pro添加配置

QT       += axcontainer

2.头文件

#include <QAxObject>

3.头文件

  1. void newExcel(const QString &fileName);// 新建一个excel
  2. void appendSheet(const QString &sheetName,int cnt);// 增加一个worksheet
  3. void setCellValue(int row,int column,const QString &value);// 向Excel单元格中写入数据
  4. void saveExcel(const QString &fileName);// 保存excel
  5. void freeExcel();// 释放excel
  6. private:
  7. Ui::TestExcel *ui;
  8. QAxObject *pApplication;
  9. QAxObject *pWorkBooks;
  10. QAxObject *pWorkBook;
  11. QAxObject *pSheets;
  12. QAxObject *pSheet;

4.实现

  1. // 新建一个excel
  2. void TestExcel::newExcel(const QString &fileName)
  3. {
  4. pApplication = new QAxObject("Excel.Application");
  5. if (pApplication == nullptr) {
  6. qWarning("pApplication\n");
  7. return;
  8. }
  9. pApplication->dynamicCall("SetVisible(bool)",false);// false不显示窗体
  10. pApplication->setProperty("DisplayAlerts",false);// 不显示任何警告信息
  11. pWorkBooks = pApplication->querySubObject("Workbooks");
  12. QFile file(fileName);
  13. if (file.exists()) {
  14. pWorkBook = pWorkBooks->querySubObject("Open(const QString&)",fileName);
  15. } else {
  16. pWorkBooks->dynamicCall("Add");
  17. pWorkBook = pApplication->querySubObject("ActiveWorkBook");
  18. }
  19. pSheets = pWorkBook->querySubObject("Sheets");
  20. pSheet = pSheets->querySubObject("Item(int)",1);
  21. }
  22. // 增加一个worksheet
  23. void TestExcel::appendSheet(const QString &sheetName,int cnt)
  24. {
  25. QAxObject *pLastSheet = pSheets->querySubObject("Item(int)",cnt);
  26. pSheets->querySubObject("Add(QVariant)",pLastSheet->asVariant());
  27. pSheet = pSheets->querySubObject("Item(int)",cnt);
  28. pLastSheet->dynamicCall("Move(QVariant)",pSheet->asVariant());
  29. pSheet->setProperty("Name",sheetName);
  30. }
  31. // 向Excel单元格中写入数据
  32. void TestExcel::setCellValue(int row,int column,const QString &value)
  33. {
  34. QAxObject *pRange = pSheet->querySubObject("Cells(int,int)",row,column);
  35. pRange->dynamicCall("Value",value);
  36. }
  37. // 保存excel
  38. void TestExcel::saveExcel(const QString &fileName)
  39. {
  40. pWorkBook->dynamicCall("SaveAs(const QString &)",QDir::toNativeSeparators(fileName));
  41. }
  42. // 释放excel
  43. void TestExcel::freeExcel()
  44. {
  45. if (pApplication != nullptr) {
  46. pApplication->dynamicCall("Quit()");
  47. delete pApplication;
  48. pApplication = nullptr;
  49. }
  50. }

5.调用

  1. void TestExcel::on_writeBtn_2_clicked()
  2. {
  3. QString fileName = "e:/测试.xlsx";
  4. newExcel(fileName);
  5. setCellValue(3,3,"Hello");
  6. setCellValue(3,6,"World");
  7. saveExcel(fileName);
  8. freeExcel();
  9. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/170600
推荐阅读
相关标签
  

闽ICP备14008679号