【笔记】 C++ 导入 Excel 表格

表格内容如图所示:
1
直接按照之前方法,选择打开 xlsx/xls 文件会出现乱码:
error

Way I 使用 txt 格式

在 Excel 中另存为 txt 文件。
1 - 1

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <conio.h>
using namespace std;

int main(int argc, char* argv[])
{
	string infile = "test_2.txt";
	vector<string> vec_str;
	ifstream input(infile);
	if (input) // ensure that the input is seccessful
	{
		string word;
		while (input >> word)
		{
			vec_str.push_back(word);
		}
	}
	else
	{
		cerr << "Cannot open file " << infile << "." << endl;
	}
	input.close();
	for (const auto& c : vec_str)
	{
		cout << c << endl;
	}
	return 0;
}

Output:
1 - 2

Way III 用 csv 格式

在 Excel 中另存为 csv 文件。
2 - 1
然后发现很麻烦的是中间是逗号隔开!!!
也就是:

Learning,C++
is,fun!

所以代码就比较复杂。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <conio.h>
using namespace std;

constexpr int MAX_LENGTH = 1024;

int main(int argc, char* argv[])
{
	string infile = "test_2.csv";
	vector<string> vec_str;
	ifstream input(infile);
	if (input) // ensure that the input is seccessful
	{
		string line_str;
		while (getline(input, line_str)) // get the whole line
		{
			string word = "";
			for (int i = 0; i != line_str.size(); i++)
			{
				if (line_str[i] != ',') // if it is ',' go to next word
				{
					word += line_str[i]; // store the word
				}
				else
				{
					vec_str.push_back(word);
					word = "";
				}
			}
			vec_str.push_back(word);
		}
	}
	else
	{
		cerr << "Cannot open file " << infile << "." << endl;
	}
	input.close();
	for (const auto& c : vec_str)
	{
		cout << c << endl;
	}
	return 0;
}

Output:
2 - 2


ALL RIGHTS RESERVED © 2020 Teddy van Jerry
欢迎转载,转载请注明出处。


See also

Teddy van Jerry 的导航页

  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值