在使用qt读取Excel文件内容的时候,使用下列方式:
worksheet->querySubObject("Cells(int,int)", j,i)->property("Value").toString();
不会报错,但读取不到数据。多次尝试发现应该将property改为dynamicCall
下面是用qt读取excel文件内容的实例。
读取方式为按列读取,以QVector<QVector<QString>>形式存储数据。
void MainWindow::getExcelContent(QVector<QVector<QString>> &result, QStringList filePathes)
{
QAxObject *excel = NULL;
QAxObject *workbooks = NULL;
QAxObject *workbook = NULL;
foreach (const QString &filePath, filePathes) {
CoInitializeEx(NULL, COINIT_MULTITHREADED);
excel = new QAxObject("Excel.Application");
QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)", 1);//读取第一个表
QAxObject *usedRange = worksheet->querySubObject("UsedRange");//有数据的矩形区域
QAxObject * rows = usedRange->querySubObject("Rows");
QAxObject * columns = usedRange->querySubObject("Columns");
int Rows = rows->property("Count").toInt();
int Cols = columns->property("Count").toInt();
//按照列方式读取数据
for(int i=1;i<=Cols; ++i){
QVector<QString> vecDataRow;
for(int j=1;j<=Rows;++j){
QString txt = worksheet->querySubObject("Cells(int,int)", j,i)->dynamicCall("Value").toString(); //获取单元格内容
vecDataRow.append(txt);
}
result.push_back(vecDataRow);
}
workbook->dynamicCall("Close()");
excel->dynamicCall("Quit()");
if(excel)
{
delete excel;
excel = NULL;
}
}
}
下面是打开文件方式,其中有单选格式方式打开文件和多选格式选择打开文件。
QString filePath = QFileDialog::getOpenFileName(
this, QStringLiteral("选择Excel文件"),"",
QStringLiteral("Excel file(*.xls *.xlsx)"));
if(filePath.isEmpty())return;
filePathes = QFileDialog::getOpenFileNames(
this, tr("Open File"),"D:/",
tr("Excel files(*.xls *.xlsx);;CSV files (*.csv)"));