WzExcel.h 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. 
  2. #ifndef _WZEXCEL_H
  3. #define _WZEXCEL_H
  4. #include <QAxObject>
  5. #include <QString>
  6. #include <QDir>
  7. #include <QFile>
  8. #include <QDebug>
  9. #include <windows.h>
  10. /*
  11. * 类:WzExcel
  12. * 作用:Qt操作Excel
  13. * 作者:欧阳伟
  14. * 日期:2017-12-19
  15. * 用法示例(需在*.pro文件中添加:QT += axcontainer)
  16. * WzExcel w("D:/hello.xlsx"); //创建对象
  17. * if(w.open()) //打开
  18. * {
  19. * //w.setCurrentWorkSheet(); //设置当前工作表
  20. * for(int i=0;i<10;i++)
  21. * {
  22. * for(int 0=1;j<10;j++)
  23. * {
  24. * w.insertValue(i,j,QString::number(i*j)); //修改内容
  25. * //w.getValue(i,j,QString::number(i*j)); //修改内容
  26. * }
  27. * }
  28. * w.save(); //保存
  29. * w.saveAs("D:/hello1.xlsx"); //另存为
  30. * }
  31. *
  32. * 说明:创建对象需传入绝对路径。
  33. */
  34. class WzExcel
  35. {
  36. public:
  37. WzExcel();
  38. //传入需要操作的Excel文件的【绝对路径】
  39. WzExcel(const QString &fileName);
  40. ~WzExcel();
  41. //设置文件名
  42. void setFileName(const QString fileName);
  43. //打开,不存在则【新建一个工作簿(保存时以传入时的文件名保存)】,成功返回true,失败返回false
  44. void open(bool visible=false,bool displayAlerts=false);
  45. //关闭
  46. void close();
  47. //设置visible,true: 可视,false: 隐藏
  48. bool setVisible(bool visible);
  49. //设置当前工作表,成功返回true,失败返回false
  50. bool setCurrentWorkSheet(const QString &sheetName=NULL);
  51. //创建工作表,成功返回true,失败返回false
  52. bool createWorkSheet(const QString &sheetName);
  53. //删除工作表,成功返回true,失败返回false
  54. bool deleteWorkSheet(const QString &sheetName);
  55. //获得指定位置的单元格内容,成功返回该值,失败返回NULL
  56. QVariant getValue(const int &row,const int &column);
  57. //插入指定位置的单元格内容,成功返回true,失败返回false
  58. bool insertValue(const int &row,const int &colum,const QString &value);
  59. //保存,成功返回true,失败返回false
  60. bool save();
  61. //另存为,成功返回true,失败返回false
  62. bool saveAs(const QString &fileName);
  63. int getRows();
  64. int getColumns();
  65. private:
  66. void release();
  67. QAxObject* getCurrentUserRange();
  68. private:
  69. QString fileName; //文件名
  70. bool isOpened;
  71. QAxObject *excel; //excel对象
  72. QAxObject *workBooks; //所有工作簿对象
  73. QAxObject *workBook; //当前工作簿对象
  74. QAxObject *workSheets; //所有工作表对象
  75. QAxObject *workSheet; //当前工作表对象
  76. QAxObject *data; //当前数据对象
  77. int startRow, startColumn;
  78. };
  79. #endif