参考文章:读写XLS文件
找了好久xls的读取库啥的,就这个比较好用。解决了出现的几个问题,并进一步封装。
定义的类
pro文件中加入 CONFIG += qaxcontainer
QtExcel//xls文件类,读写都定义在这里
PathGet//定义了一个文件读取
原代码中,只要打开文件必会保存,由此会引发错误,因此在原代码上进行了一系列修改,仅仅再写入后需要保存。
ps:保存时会询问是否替代原文件,一定要选择是,否则会有错误。
QtExcel中原作者定义了两种读取数据方法,但是我只使用过其中了其中的一种,即按行列号读取,因此,在这里的读取用的都是这个。
读取返回的是Qt 中特有的QVariant类,可存储各种数据,但是貌似不支持c/c++ 风格的字符串?
因此,定义了一系列的转化方法,将QVariant对象转化为QString,再转化为string,亲测中文不会乱码。
接下来就是上代码了
PathGet:
#ifndef PATHGET_H
#define PATHGET_H
#include <windows.h>
#include <Commdlg.h>
#include <stdio.h>
#include <QString>
const int MAX_PATHL = 100;
class PathGet{
public:
static QString getPath(wchar_t* filetype);
};
#endif // FILEPATHGET_H
#include"PathGet.h"
int FileDialog(wchar_t *path,wchar_t* filetype)
{
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn); // 结构大小
ofn.lpstrFile = path; // 路径
ofn.nMaxFile = MAX_PATH; // 路径大小
ofn.lpstrFilter = filetype;//"All\0*.*\0Text\0*.TXT\0"; // 文件类型
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
return GetOpenFileName(&ofn);
}
QString PathGet:: getPath(wchar_t* filetype){
wchar_t path[MAX_PATHL]={
0};
if(FileDialog(path,filetype)){
return QString::fromWCharArray(path);
}
else return NULL;
}
GetData:
#ifndef GETDATA_H
#define GETDATA_H
#include "PathGet.h"
#include "QtExcel.h"
#include <QApplication>
#include <QDebug>
#include<iostream>
#include<stdio.h>
struct pos{
int row;
int col;
pos(int x,int y){
row =x,col=y;
}
pos(int a[]){
row =a[0];
col =a[1];
}
};
class GetData{
private :
QtExcel &xlsFile;
public : GetData(QtExcel &a);//构造函数
int GetInt(pos a);
double GetDouble(pos a);
std::string Getstring(pos a);
QVariant readCell(pos a);//读取单元格
};
#endif // GETDATA_H
#include "GetData.h"</