读取csv文件(C#,C++)

C++代码

#include <fstream>
#include <sstream>
#include <iostream>

using namespace std;
void ReadCSV()
{
    ifstream inf;
    inf.open("test.csv", ifstream::in);         
  
    string line;	
    int j=0;   
    size_t comma = 0;
    size_t comma2 = 0;
      
    getline(inf,line);//第一行是列名,排除
	while (!inf.eof())
	{
		getline(inf,line);
		comma = line.find(',',0);//默认行内分割符为逗号,若为空格,做相应调整
		while (comma < line.size() && j != marknum+2)
			{
				comma2 = line.find(',',comma + 1);				
			
				cout<<atof(line.substr(comma + 1,comma2-comma-1).c_str())<<endl;//读出一个列元素,并将其转化成float类型
				
				comma = comma2;
				j++;
			}			
			j = 0;
			
		}


	}
  
    inf.close();
}
C#代码

  private DataTable GetCsvData(string filePath, string fileName)
        {

            string path = filePath + "\\" + fileName + ".csv";

            string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};
            Dbq=" + filePath + ";Extensions=csv";
            try
            {
                using (OdbcConnection odbcConn = new OdbcConnection(connString))
                {

                    odbcConn.Open();

                    OdbcCommand oleComm = new OdbcCommand();

                    oleComm.Connection = odbcConn;

                    oleComm.CommandText = "select * from [" + fileName + "#csv]";

                    OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);

                    DataSet ds = new DataSet();

                    adapter.Fill(ds, fileName);

                    odbcConn.Close();

                    return ds.Tables[0];
                }
            }

            catch (Exception ex)
            {

                throw ex;
            }
        }
 private void ReadCSV()
        {
            DataTable dt = GetCsvData("path", "filename");
            int sidx = 0;           
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow drOperate = dt.Rows[i];
                for (int j = 0; j < drOperate.ItemArray.Length; j++)                   
                    {
                        cout<<drOperate[j])<<endl;
                    }                    
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值