c++读写Excel文件

#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;  
}  

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

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

  • 9
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值