说明
之前的那个版本是有很多模板函数但又不是模板类,看起来非常的难受,所以专门改写了一个纯模板类的Excel数组存储的程序。
使用说明
使用时需要将cpp文件和h文件放置在同一文件夹下,但同时cpp文件不要加入到工程中,否则必然报错。
程序
//CXEcelT.h
#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <CDebug.h>
using namespace std;
template <class T>
class CExcelT
{
public:CExcelT(string str);
void modifyName(string str);
~CExcelT(){ }
vector<vector<T>> read();
bool write(vector<vector<T>> vec);
private: string name;
};
#include "CExcelT.cpp"
//CExcelT.cpp
#include "pch.h"
#include "CExcelT.h"
template<class T>
inline CExcelT<T>::CExcelT(string str)
{
name = str;
}
template<class T>
inline void CExcelT<T>::modifyName(string str)
{
name = str;
}
template<class T>
inline vector<vector<T>> CExcelT<T>::read()
{
ifstream myfile(name.c_str());
if (!myfile.is_open())
{
CDebug() << "can not open this file";
return { };
}
string line;
int w, h;
getline(myfile, line);
string filed;
istringstream mystr(line);
getline(mystr, filed, ',');
w = atoi(filed.c_str());
getline(mystr, filed, ',');
h = atoi(filed.c_str());
vector<vector<T>> vec;
vec.resize(w);
for (int i = 0; i < w; i++)
{
vec[i].resize(h);
}
for (int i = 0; i < w; i++)
{
string line;
getline(myfile, line);
istringstream mystr(line);
for (int j = 0; j < h; j++)
{
string filed;
getline(mystr, filed, ',');
vec[i][j] = filed;
}
}
myfile.close();
return vec;
}
template<class T>
inline bool CExcelT<T>::write(vector<vector<T>> vec)
{
if (vec.empty()) //空的,不做任何处理
return false;
if (name.empty())
return false;
unsigned int w = vec.size();
unsigned int h = vec[0].size();
ofstream outfile(name.c_str());
if (!outfile.is_open())
{
CDebug() << "can not open this file";
return false;
}
outfile.clear();
outfile << w << "," << h << "\n";
for (unsigned int i = 0; i < w; i++)
{
for (unsigned int j = 0; j < h; j++)
{
outfile << vec[i][j];
if (j != h - 1)
outfile << ",";
}
outfile << "\n";
}
outfile.close();
return true;
}
最后
这里写入数据是有一定的格式的,如果需要对格式进行一定的修改,应当在原有程序的基础上进行必要的修改操作。