2013-05-17 158 views
14

我想讀取CSV文件的內容並創建數據集。 我想是這樣的:從CSV文件填充數據集

var lines = File.ReadAllLines("test.csv").Select(a => a.Split(';')); 
DataSet ds = new DataSet(); 
ds.load(lines); 

但顯然這是不正確的。

+0

爲什麼你認爲這是不正確的? – Damith

回答

13

你需要運行對CSV文件SELECT語句來填充數據集:

編輯:這裏是來自http://carllbrown.blogspot.co.uk/2007/09/populate-dataset-from-csv-delimited_18.html

string FileName = ... 
OleDbConnection conn = new OleDbConnection 
     ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + 
     Path.GetDirectoryName(FileName) + 
     "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\""); 

conn.Open(); 

OleDbDataAdapter adapter = new OleDbDataAdapter 
     ("SELECT * FROM " + Path.GetFileName(FileName), conn); 

DataSet ds = new DataSet("Temp"); 
adapter.Fill(ds); 

conn.Close(); 
+0

1+的方法,但你最好添加示例代碼,而不是添加鏈接到博客文章 – Damith

+0

那麼ds創建,但我不能訪問它/看到csv文件中的數據 –

4

您可以使用圖書館像Fast CSV Reader然後

using System.IO; 
using LumenWorks.Framework.IO.Csv; 
void ReadCsv() 
{ 
    // open the file "data.csv" which is a CSV file with headers 
    using (CsvReader csv = new CsvReader(
          new StreamReader("data.csv"), true)) 
    { 
     myDataRepeater.DataSource = csv; 
     myDataRepeater.DataBind(); 
    } 
} 
一些示例代碼
+1

我不明白爲什麼這不是upvoted。這是一個偉大的助手。例如,將您的CSV文件(用逗號分隔)的圖像在[「hello」,「hi」,「hello,你好嗎」等字段中也有一個逗號。如果使用String.Split(','),則最後一個條目將被拆分爲兩個,但它應該是一個。除了其他的東西外,CsvReader會爲你處理這個問題。所以,強烈推薦。 – pixel

17

您需要將參考Microsoft.VisualBasic.dll使用TextFieldParser類。

private static DataTable GetDataTabletFromCSVFile(string csv_file_path) 
     { 
      DataTable csvData = new DataTable(); 
      try 
      { 
       using(TextFieldParser csvReader = new TextFieldParser(csv_file_path)) 
       { 
        csvReader.SetDelimiters(new string[] { "," }); 
        csvReader.HasFieldsEnclosedInQuotes = true; 
        string[] colFields = csvReader.ReadFields(); 
        foreach (string column in colFields) 
        { 
         DataColumn datecolumn = new DataColumn(column); 
         datecolumn.AllowDBNull = true; 
         csvData.Columns.Add(datecolumn); 
        } 
        while (!csvReader.EndOfData) 
        { 
         string[] fieldData = csvReader.ReadFields(); 
         //Making empty value as null 
         for (int i = 0; i < fieldData.Length; i++) 
         { 
          if (fieldData[i] == "") 
          { 
           fieldData[i] = null; 
          } 
         } 
         csvData.Rows.Add(fieldData); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
      } 
      return csvData; 
     } 
     } 

請參見本文的詳細信息:http://www.morgantechspace.com/2013/08/how-to-read-data-from-csv-file-in-c.html

+0

TextFieldParser從哪裏來? –

+1

嗨@RobSedgwick,你需要添加引用Microsoft.VisualBasic.dll來使用TextFieldParser類。 – kombsh

0

如果你只是想快速創建(從Excel或直接粘貼)填充了樣本數據從一個CSV文件中的數據表中打轉轉或原型,然後你可以使用我的分支先生的數據轉換器 - 我最近添加了輸出逗號和製表符分隔數據到C#DataTable的功能。

http://thdoan.github.io/mr-data-converter/

0

我寫了下面這五種方法將變成一個CSV文件導入數據表。

它們的設計考慮了可選的引號(例如,「符號),併成爲多才多藝儘可能不使用其他庫:否則

Warning[] warnings; 
    string[] streamids; 
    string mimeType; 
    string encoding; 
    string filenameExtension; 

    byte[] bytes = rvMain.ServerReport.Render("csv", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); 

    string CsvBody = System.Text.Encoding.UTF8.GetString(bytes); 

    DataTable dt = GetDataTableFromCsvString(CsvBody,true); 

public static DataTable GetDataTabletFromCSVFile(string filePath, bool isHeadings) 
    { 
     DataTable MethodResult = null; 
     try 
     { 
      using (TextFieldParser TextFieldParser = new TextFieldParser(filePath)) 
      { 
       if (isHeadings) 
       { 
        MethodResult = GetDataTableFromTextFieldParser(TextFieldParser); 

       } 
       else 
       { 
        MethodResult = GetDataTableFromTextFieldParserNoHeadings(TextFieldParser); 

       } 

      } 

     } 
     catch (Exception ex) 
     { 
      ex.HandleException(); 
     } 
     return MethodResult; 
    } 

    public static DataTable GetDataTableFromCsvString(string csvBody, bool isHeadings) 
    { 
     DataTable MethodResult = null; 
     try 
     { 
      MemoryStream MemoryStream = new MemoryStream(); 


      StreamWriter StreamWriter = new StreamWriter(MemoryStream); 

      StreamWriter.Write(csvBody); 

      StreamWriter.Flush(); 


      MemoryStream.Position = 0; 


      using (TextFieldParser TextFieldParser = new TextFieldParser(MemoryStream)) 
      { 
       if (isHeadings) 
       { 
        MethodResult = GetDataTableFromTextFieldParser(TextFieldParser); 

       } 
       else 
       { 
        MethodResult = GetDataTableFromTextFieldParserNoHeadings(TextFieldParser); 

       } 

      } 

     } 
     catch (Exception ex) 
     { 
      ex.HandleException(); 
     } 
     return MethodResult; 
    } 

    public static DataTable GetDataTableFromRemoteCsv(string url, bool isHeadings) 
    { 
     DataTable MethodResult = null; 
     try 
     { 
      HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
      HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 

      StreamReader StreamReader = new StreamReader(httpWebResponse.GetResponseStream()); 

      using (TextFieldParser TextFieldParser = new TextFieldParser(StreamReader)) 
      { 
       if (isHeadings) 
       { 
        MethodResult = GetDataTableFromTextFieldParser(TextFieldParser); 

       } 
       else 
       { 
        MethodResult = GetDataTableFromTextFieldParserNoHeadings(TextFieldParser); 

       } 

      } 

     } 
     catch (Exception ex) 
     { 
      ex.HandleException(); 
     } 
     return MethodResult; 
    } 


    private static DataTable GetDataTableFromTextFieldParser(TextFieldParser textFieldParser) 
    { 
     DataTable MethodResult = null; 
     try 
     { 
      textFieldParser.SetDelimiters(new string[] { "," }); 

      textFieldParser.HasFieldsEnclosedInQuotes = true; 


      string[] ColumnFields = textFieldParser.ReadFields(); 

      DataTable dt = new DataTable(); 

      foreach (string ColumnField in ColumnFields) 
      { 
       DataColumn DataColumn = new DataColumn(ColumnField); 

       DataColumn.AllowDBNull = true; 

       dt.Columns.Add(DataColumn); 

      } 


      while (!textFieldParser.EndOfData) 
      { 
       string[] Fields = textFieldParser.ReadFields(); 


       for (int i = 0; i < Fields.Length; i++) 
       { 
        if (Fields[i] == "") 
        { 
         Fields[i] = null; 

        } 

       } 

       dt.Rows.Add(Fields); 

      } 

      MethodResult = dt; 

     } 
     catch (Exception ex) 
     { 
      ex.HandleException(); 
     } 
     return MethodResult; 
    } 

    private static DataTable GetDataTableFromTextFieldParserNoHeadings(TextFieldParser textFieldParser) 
    { 
     DataTable MethodResult = null; 
     try 
     { 
      textFieldParser.SetDelimiters(new string[] { "," }); 

      textFieldParser.HasFieldsEnclosedInQuotes = true; 

      bool FirstPass = true; 

      DataTable dt = new DataTable(); 

      while (!textFieldParser.EndOfData) 
      { 
       string[] Fields = textFieldParser.ReadFields(); 

       if(FirstPass) 
       { 
        for (int i = 0; i < Fields.Length; i++) 
        { 
         DataColumn DataColumn = new DataColumn("Column " + i); 

         DataColumn.AllowDBNull = true; 

         dt.Columns.Add(DataColumn); 

        } 

        FirstPass = false; 

       } 

       for (int i = 0; i < Fields.Length; i++) 
       { 
        if (Fields[i] == "") 
        { 
         Fields[i] = null; 

        } 

       } 

       dt.Rows.Add(Fields); 

      } 

      MethodResult = dt; 

     } 
     catch (Exception ex) 
     { 
      ex.HandleException(); 
     } 
     return MethodResult; 
    } 

如果像我一樣,你從報告服務,然後保存,你應該使用這樣的,所有你需要做的是:

bool IsHeadings = true; //Does the data include a heading row? 

    DataTable dt = GetDataTableFromCsvString(CsvBody, IsHeadings); 

或直接從csv文件使用

bool IsHeadings = true; //Does the data include a heading row? 

    DataTable dt = GetDataTabletFromCsvFile(FilePath, IsHeadings) 

或者用存儲遠程

bool IsHeadings = true; //Does the data include a heading row? 

    DataTable dt = GetDataTabletFromRemoteCsv(Url, IsHeadings) 

將數據集數據表的集合的CSV文件,因此創建一個像這樣:在此解決

DataSet ds = new DataSet(); 

    ds.Tables.Add(dt); 
1

逗號(,)問題代碼

Works即使如果您在單元格之間添加逗號(,)

閱讀CSV文件代碼:

public MainWindow() 
       { 
        InitializeComponent(); 

        DataTable dtDataSource = new DataTable(); 

        string[] fileContent = File.ReadAllLines(@"..\\Book1.csv"); 

        if (fileContent.Count() > 0) 
        { 
         //Create data table columns dynamically 
         string[] columns = fileContent[0].Split(','); 

         for (int i = 0; i < columns.Count(); i++) 
         { 
          dtDataSource.Columns.Add(columns[i]); 
         } 

         //Add row data dynamically 
         for (int i = 1; i < fileContent.Count(); i++) 
         { 
          string[] rowData = fileContent[i].Split(','); 
          string[] realRowData = new string[columns.Count()]; 
          StringBuilder collaboration = new StringBuilder(); 
          int v = 0; 

          //this region solves the problem of a cell containing ",". 
          #region CommaSepProblem 
          for (int j = 0, K = 0; j < rowData.Count(); j++, K++) 
          { 
           if ((rowData[j].Count(x => x == '"') % 2 == 0))//checks if the string contains even number of DoubleQuotes 
           { 
            realRowData[K] = quotesLogic((rowData[j])); 

           } 
           else if ((rowData[j].Count(x => x == '"') % 2 != 0))//If Number of DoubleQuotes are ODD 
           { 
            int c = rowData[j].Count(x => x == '"'); 
            v = j; 

            while (c % 2 != 0)//Go through all the next array cell till it makes EVEN Number of DoubleQuotes. 
            { 
             collaboration.Append(rowData[j] + ","); 
             j++; 
             c += rowData[j].Count(x => x == '"'); 

            } 

            collaboration.Append(rowData[j]); 
            realRowData[K] = quotesLogic(collaboration.ToString()); 
           } 
           else { continue; } 
          } 
          #endregion 
          dtDataSource.Rows.Add(realRowData); 
         } 
         if (dtDataSource != null) 
         { 
          //dataGridView1 = new DataGridView(); 
          dataGrid1.ItemsSource = dtDataSource.DefaultView; 
         } 
        } 
       } 

方法需要添加:

string quotesLogic(string collaboration) 
    { 
     StringBuilder after = new StringBuilder(collaboration); 

     if (after.ToString().StartsWith("\"") && after.ToString().EndsWith("\""))//removes 1st and last quotes as those are system generated 
     { 
      after.Remove(0, 1); 
      after.Remove(after.Length - 1, 1); 
      int count = after.Length - 1; 
      //FACT: if you try to add DoubleQuote in a cell in excel. It'll save that quote as 2 times DoubleQuote(Like "") which means first DoubleQuote is to give instruction to CPU that the next DoubleQuote is not system generated. 
      while (count > 0)//This loop find twice insertion of 2 DoubleQuotes and neutralise them to One DoubleQuote. 
      { 
       if (after[count] == '"' && after[count - 1] == '"') 
       { 
        after.Remove(count, 1); 
       } 
       count--; 
      } 
     } 

     return after.ToString(); 
    }