关闭

c++读写Excel文件

194人阅读 评论(0) 收藏 举报
分类:
#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;  
}  

输出结果:这里写图片描述

写的时候个字段要用逗号分隔,用空格不行;读的时候一次要读一行

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10960次
    • 积分:364
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    最新评论