1、将excel表格另存为csv格式,比如文件内容如下:
2、我们的目的是在身份证号后面一列加上年龄。
3、代码实现的功能是批量处理多个类似的文件,自动计算年龄。
4、注意将处理的文件放在工程work目录下,且在工程目录下新建一个out目录。
5、main.cpp:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <io.h>
using namespace std;
string Trim(string& str)
{
str.erase(0,str.find_first_not_of(" \t\r\n"));
str.erase(str.find_last_not_of(" \t\r\n") + 1);
return str;
}
int work(string filenme)
{
string infilename = "work/";
infilename += filenme;
ifstream fin(infilename);
string outfilename = "out/";
outfilename = outfilename + filenme;
ofstream fout(outfilename);
int idNumCol = 3;//身份证号在第几列
int firstRowFlag = 1;
int yearIndex = 0;
int year;
int mon;
int day;
int age;
//当前时间
int rYear = 2017;
int rMon = 9;
int rDay = 1;
cout << endl;
string line;
while (getline(fin, line)) {
ostringstream ost;
//cout << line << endl;
if(firstRowFlag == 1)
{
line = line + ',' + "年龄";
fout << line << endl;
firstRowFlag = 0;
continue;
}
istringstream sin(line);
vector<string> fields;
string field;
while (getline(sin, field, ',')) {
fields.push_back(field);
}
if(fields[idNumCol-1] == "")
continue;
string num = Trim(fields[idNumCol-1]);
//找到第一个数字,然后计算year的位置
for (int i = 0; i <= num.size() - 1;i++)
{
if (num[i] >= '0'&&num[i] <= '9')
{
yearIndex = i + 6;
break;
}
}
//计算他的出生日期
year = (num[yearIndex]-48)*1000 + (num[yearIndex+1]-48)*100 + (num[yearIndex+2]-48)*10 + (num[yearIndex+3]-48);
mon = (num[yearIndex+4]-48)*10 + (num[yearIndex+5]-48);
day = (num[yearIndex+6]-48)*10 + (num[yearIndex+7]-48);
//年龄计算
age = rYear-year;
if(mon > rMon)
{
age--;
}
else if(mon == rMon)
{
if(day > rDay)
{
age--;
}
}
ost << age;
line = line + ',';
line = line + ost.str();
cout << line << endl;
fout << line << endl;
}
return 0;
}
int main(int argc, char* argv[])
{
_finddata_t file;
long lf;
if((lf = _findfirst("work//*.*", &file))==-1l)
{
cout<<"文件没有找到!\n";
}
else
{
cout<<"\n文件列表:\n";
while( _findnext( lf, &file ) == 0 )
{
cout<<file.name;
if(file.attrib == _A_NORMAL)
cout<<" 普通文件 ";
else if(file.attrib == _A_RDONLY)
cout<<" 只读文件 ";
else if(file.attrib == _A_HIDDEN )
cout<<" 隐藏文件 ";
else if(file.attrib == _A_SYSTEM )
cout<<" 系统文件 ";
else if(file.attrib == _A_SUBDIR)
{
cout<<" 子目录 ";
//do something
}
else
{
cout<<" 存档文件 ";
work(file.name);
}
cout<<endl;
}
}
_findclose(lf);
getchar();
return 0;
}
5、结果如下: