C++实现Excel存储数组2

C++实现Excel存储数组2

说明

之前的那个版本是有很多模板函数但又不是模板类,看起来非常的难受,所以专门改写了一个纯模板类的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;
}

最后

这里写入数据是有一定的格式的,如果需要对格式进行一定的修改,应当在原有程序的基础上进行必要的修改操作。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值