c++讀寫Excel檔案
阿新 • • 發佈:2019-02-02
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
//開啟要輸入的檔案
ofstream oFile;
oFile.open("1.csv", ios::out | ios::trunc); // 這樣就很容易的輸出一個需要的excel 檔案
oFile << "姓名" << "," << "年齡" << "," << "班級" << "," << "班主任" << endl;
oFile << "張三" << "," << "22" << "," << "1" << "," << "JIM" << endl;
oFile << "李四" << "," << "23" << "," << "3" << "," << "TOM" << endl;
oFile.close();
//開啟要輸出的檔案
ifstream iFile("1.csv");
string s1,s2,s3,s4;
while(getline(iFile,s1))
{
cout<<s1<<endl;
cout<<endl;
}
iFile.close();
//逐個提取以逗號分隔的詞
ifstream inf;
inf.open("1.csv" , ifstream::in);
const int cnt = 3; //一行有3個逗號
int j = 0;
size_t comma = 0;
size_t comma2 = 0;
while ( getline(inf,s2) )
{
comma = s2.find(',',0);
cout<<s2.substr(0,comma).c_str()<<'\t';
while (comma < s2.size() && j != cnt-1)
{
comma2 = s2.find(',',comma + 1);
cout<<s2.substr(comma + 1,comma2-comma-1).c_str()<<'\t';
++j;
comma = comma2;
}
cout<<endl;
j = 0;
}
inf.close();
return 0;
}
輸出結果:
寫的時候個欄位要用逗號分隔,用空格不行;讀的時候一次要讀一行