今天主要实现功能是点击按钮可以选择一个excel表格文件并读取表格里面的内容。
代码链接:https://download.csdn.net/download/weixin_39770778/10574778
我们先用QtCreator新建一个工程(工程路径不能出现中文)。然后添加一个名为importfile的类。贴出importfile.h
#ifndef IMPORTFILES_H
#define IMPORTFILES_H
#include <QStandardItemModel>
#include <QStandardItem>
#include <QString>
#include <QFile>
#include <QDir>
#include <QFileDialog>
#include <QStandardPaths>
#include <QMessageBox>
#include <QThread>
#include <ActiveQt\QAxObject>
#include <ActiveQt\QAxWidget>
#include <QMessageBox>
#include <vector>
#include <string>
#include <qt_windows.h>
#include<Qdebug>
using namespace std;
class importFiles : public QThread //为了不和界面操作冲突,用另外一个进程了进行读取excel
{
public:
importFiles();
~importFiles();
public:
int GetFileContent(QString filename);
int m_state = 2;
vector<vector<QString> > fileContent;
};
#endif // !IMPORTFILES_H
接下来是importfiles.cpp的内容
#include "importFiles.h"
importFiles::importFiles()
{
}
importFiles::~importFiles()
{
}
int importFiles::GetFileContent(QString filename)
{
QString Text;
CoInitializeEx(NULL, COINIT_MULTITHREADED);
//fileContent.clear();
QAxObject* excel = new QAxObject();
if (!excel->setControl("Excel.Application"))//判断是否成功连接excel文件
{
delete excel;
excel = NULL;
CoUninitialize();
return -2;
}
excel->setProperty("Visible", false);
QAxObject* work_books = excel->querySubObject("WorkBooks");
work_books->dynamicCall("Open (const QString&)", filename);
if (work_books == NULL)
{
excel->dynamicCall("Quit(void)"); //退出
delete excel;
excel = NULL;
CoUninitialize();
return -1;
}
QAxObject* work_book = excel->querySubObject("ActiveworkBook");
if (work_book == NULL)
{
work_books->dynamicCall("Close(Boolean)", false); //关闭文件
excel->dynamicCall("Quit(void)"); //退出
delete work_books;
work_books = NULL;
delete excel;
excel = NULL;
CoUninitialize();
return -1;
}
QAxObject* work_sheets = work_book->querySubObject("Worksheets(int)", 1); //Sheets也可换用WorkSheets
QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", 1);
QAxObject *used_range = work_sheet->querySubObject("UsedRange");
QAxObject *rows = used_range->querySubObject("Rows");
QAxObject *columns = used_range->querySubObject("Columns");
int row_count = rows->property("Count").toInt(); //获取行数
int col_count = columns->property("Count").toInt(); //获取列数
for (int i = 1; i < row_count; i++)
{
for (int j = 0; j < col_count; j++)
{
Text = work_sheet->querySubObject("Cells(int,int)",i+1,j+1)->dynamicCall("Value").toString();
qDebug() <<Text;
}
}
work_books->dynamicCall("Close(Boolean)", false);
excel->dynamicCall("Quit(void)"); //退出
delete work_books;
work_books = NULL;
delete excel;
excel = NULL;
CoUninitialize();
return 1;
}
然后在界面ui上面拖一个按钮,转到槽后的内容如下:
m_file =QFileDialog::getOpenFileName(this, "打开", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), "表格文件( *.xlsx)");
//这里是打开文件里面包括了你要打开的文件格式
impor->GetFileContent(m_file); //调用imporfile类里面的读取excel文件的内容函数
因为我们用到了QAxObject 类,所以我们要在pro文件里面添加一行 QT += axcontainer