2011-01-20 6 views
1

Dans mon site Web, j'ai beaucoup de fichiers CSV dont j'ai besoin pour analyser et insérer leurs données dans ma base de données MySQL.Comment analyser un fichier CSV dans un site Web ASP.NET?

Comment puis-je analyser le contenu CSV de mon site Web par programmation?

+0

Très proche de http://stackoverflow.com/questions/4748082/how-to-download-the-csv-file-in -mon-site-d'-autre-serveur-web. Seulement quelques mots différents. –

+3

L'autre article concerne le téléchargement et non l'analyse. –

+1

cela n'a rien à voir avec asp.net, il s'agit seulement d'analyser. –

Répondre

0

obtenu la réponse:

je l'ai fait avec succès l'analyse de mon fichier CSV à l'aide du code ci-dessous:

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

vous devez également ajouter le code suivant sous le tag Configurations dans votre fichier web.config:

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

Hope this helps quelqu'un :)

6

Je recommande la recherche à la TextFieldParserClass en .Net. Vous devez inclure

Imports Microsoft.VisualBasic.FileIO.TextFieldParser 

Voici un échantillon rapide:

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 
Questions connexes