C++| excel存取

基础知识:stream

介绍stream(流)是因为后面介绍excel文件读取使用的是fstream,所以补全一些stream相关知识有利于理解。

stream类是C++中的“流”类,所有的I/O都是以“流”为基础。
stream的两个最基础的操作就是插入器(cout)和析取器(cin)。
stream在C++中的主要三个头文件库是iostream、fstream和sstream。

iostream:io就是Input/Output的缩写,主要是负责与控制台输入输出打交道。
入门过C++,第一次学C++输出“Hellow World”的时候用的就是“cout<<“Hellow World”<<endl”,第一次获取用户输入的时候就是“cin>>input;”,用的cout和cin就是在用iostream的功能。

fstream:file stream文件流可以操作文件。写入用ofstream,读取用ifstream,后面excel的存取部分会看到详细的使用。

sstream:string stream负责和string输入输出打交道。在excel读部分会使用到,stringstream会有很多很方便的string处理功能。

excel存

使用的时候,引用头文件为fstream。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void excel_write() {
	string excelName = "./text.xls";// 带文件路径+文件名+文件后缀
	ofstream outfile(excelName);// 创建流,并打开文件
	if (!outfile.is_open()) {
		cout << "打开失败!" << endl;
		return ;
	}
	int row = 50;// 行
	int col = 5;// 列
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			// '\n'换行;'\t'换列
			outfile << i*col+j << (j == (col - 1) ? '\n' : '\t');// 写入到excel表中
		}
	}
	outfile.close();
}

excel表中的换行和换列,除了\n换行\t换列,还可以endl换行逗号换列。

// 方法二
// endl换行;,换列
outfile << "name"<< ","<<"age"<<","<<"class"<<endl;// 写入到excel表中一行

excel读

excel读取的时候,通常都不知道具体要读取的内容有多少,所以会用vector不定长数据来进行数据存储。

注意stringstream使用的头文件是sstream。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;

void excel_read() {
	ifstream ifs;// 创建流
	ifs.open("./text.xls", ios::in);//打开文件
	if (!ifs.is_open()) {
		cout << "打开失败!" << endl;
		return ;
	}
	vector<string>item;// 不定长数组存放数据内容
	string temp_row;// 临时存放一行数据
	string temp_item;
	while (getline(ifs, temp_row)) {
		// 每行中的数据是以'\t'分割,利用stringstream进行分割
		stringstream temp(temp_row);
		while (getline(temp, temp_item, '\t')) {
			item.push_back(temp_item);
			cout << temp_item << "\t";
		}
		cout << "\n";
	}
	ifs.close();
}
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值