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();
}