直接看代码:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void writeJson();
void readJson();
private:
Ui::Widget *ui;
};
#endif // WIDGET_
#include "excelbase.h"
#include <QFile>
#include <QDebug>
excelBase::excelBase(QString xlsFilePath, QObject *parent)
{
excel = NULL;
workBooks = NULL;
workBook = NULL;
sheets = NULL;
sheet = NULL;
excel = new QAxObject("Excel.Application", parent);
workBooks = excel->querySubObject("Workbooks");
QFile file(xlsFilePath);
if(file.exists())
{
workBooks->dynamicCall("Open(const QString&)", xlsFilePath);
workBook = excel->querySubObject("ActiveWorkBook");
sheets = workBook->querySubObject("WorkSheets");
sheet = workBook->querySubObject("WorkSheets(int)", 1);
}
}
excelBase::~excelBase()
{
close();
}
int excelBase::sheetCount()
{
return sheets->property("Count").toInt();
}
QString excelBase::getSheetName(int sheetIndex)
{
sheet = workBook->querySubObject("WorkSheets(int)", sheetIndex);
return sheet->property("Name").toString();
}
QAxObject *excelBase::getWorkBook()
{
return workBook;
}
void excelBase::save()
{
workBook->dynamicCall("Save()");
}
void excelBase::close()
{
excel->dynamicCall("Quit()");
delete sheet;
delete sheets;
delete workBook;
delete workBooks;
delete excel;
excel = NULL;
workBooks = NULL;
workBook = NULL;
sheets = NULL;
sheet = NULL;
}
void excelBase::readAll(int index)
{
sheet = workBook->querySubObject("WorkSheets(int)", index);
if(sheet->isNull())
return;
QAxObject* range = sheet->querySubObject("UsedRange");//获取该sheet的使用范围对象
QVariant var = range->dynamicCall("Value");
delete range;
QVariantList varRows = var.toList();
QString str1, str2, str3, str4;
if(varRows.isEmpty())
return;
const int rowCount = varRows.size();
for(int i = 1; i < rowCount;++i)
{
QVariantList rowData = varRows[i].toList();
str1 = rowData[0].toString();
str2 = rowData[1].toString();
str3 = rowData[2].toString();
str4 = rowData[3].toString();
qDebug() << str1 << str2 << str3 << str4;
}
}