How to parse a CSV file in an ASP.NET website?

后端 未结 3 1699
别那么骄傲
别那么骄傲 2021-01-07 08:35

In my website, I have many CSV files that I need to parse and insert their data into my MySQL database.

How can I parse the CSV in my website programmatically?

3条回答
  •  轮回少年
    2021-01-07 08:55

    Got the Answer:

    I have successfully done the parsing of my CSV file using the below code:

    _nNrRowsProccessed = 0;
    
        string connectionString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+ConfigurationManager.AppSettings["csvFolder"]+";";
    
        OdbcConnection conn = new OdbcConnection(connectionString);
    
        try
        {
            conn.Open();
    
            string strFileName = ConfigurationManager.AppSettings["csvFileName"];
            string strSQL = "Select * from " + strFileName;
    
            OdbcCommand cmd = new OdbcCommand();
            cmd.Connection = conn;
            cmd.CommandText = strSQL;
            cmd.CommandType = CommandType.Text;
    
            OdbcDataReader reader = cmd.ExecuteReader();
            string strLine = null;
    
            MasterCalendar_DB.OpenMySQLConnection();
    
            while (reader.Read())
            {
                // insert data into mastercalendar
                strLine = reader[0].ToString();
                string[] arLine = strLine.Split(';');
    
                string strAgencyPropertyID = arLine[0];
                DateTime dt = DateTime.Parse(arLine[1]);
                Int64 nDate = (Int64)Util.ConvertToUnixTimestamp(dt);
                String strAvailability = (arLine[2]);
    
                _nNrRowsProccessed++;
                MasterCalendar_DB.Insert(strAgencyPropertyID, nDate, strAvailability);
            }
        }
        finally
        {
            conn.Close();
            MasterCalendar_DB.CloseMySQLConnection();
        }
    

    Also you need to add the following code under Configurations tag into your web.config file:

    Hope this helps someone :)

提交回复
热议问题