操作excel表格通過身份證號計算年齡

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、結果如下:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章