【问题标题】:How to parse a CSV file in an ASP.NET website?如何解析 ASP.NET 网站中的 CSV 文件?
【发布时间】:2011-01-20 14:10:19
【问题描述】:

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

如何以编程方式解析我网站中的 CSV?

【问题讨论】:

标签: .net parsing csv


【解决方案1】:

我建议查看 .Net 中的 TextFieldParserClass。你需要包括

Imports Microsoft.VisualBasic.FileIO.TextFieldParser

这是一个简单的示例:

Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
Dim CurrentRecord As String() ' this array will hold each line of data
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True

' parse the actual file
Do While Not afile.EndOfData
    Try
        CurrentRecord = afile.ReadFields
    Catch ex As FileIO.MalformedLineException
        Stop
    End Try
Loop

【讨论】:

    【解决方案2】:

    这是一个非常好的 CSV 解析器。您只需遍历数据集即可将其放回数据库。

    http://www.codeproject.com/KB/database/CsvReader.aspx

    【讨论】:

    • 是的。谷歌搜索时,“c# csv parser”和“c# csv reader”均获得第一名。
    【解决方案3】:

    得到答案:

    我已使用以下代码成功解析了我的 CSV 文件:

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

    您还需要将 Configurations 标签下的以下代码添加到您的 web.config 文件中:

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

    希望这可以帮助某人:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      相关资源
      最近更新 更多