如何解析一个ASP.NET网站的CSV文件?文件、网站、ASP、NET

2023-09-03 15:35:01 作者:悠悠我心

在我的网站,我有许多我需要解析并插入他们的数据到我的MySQL数据库的CSV文件。

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

我怎样才能解析CSV在我的网站编程?

How can I parse the CSV in my website programmatically?

推荐答案

得到了答案:

我已经成功地做​​到用低于code我的CSV文件的解析:

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();
    }

同时,你需要添加在配置标签下code到你的web.config文件:

<的appSettings>    <添加键=csvFileName值=< FILE_NAME>的.csv/>    <添加键=csvFolder值=<文件路径>/>    < /的appSettings>

<appSettings> <add key="csvFileName" value="<file_name>.csv" /> <add key="csvFolder" value="<filePath>"/> </appSettings>

希望这可以帮助别人:)

Hope this helps someone :)