2010-12-07 63 views
1

我有一個要求,即必須從CSV文件中讀取存儲在我的磁盤中的數據,並將CSV中的所有數據放入到.Net數據表中。將數據從CSV讀取到.net數據表

我該怎麼辦呢?

+0

可能重複[如何讀取CSV文件導入一個.NET數據表( http://stackoverflow.com/questions/1050112/how-to-read-a-csv-file-into-a-net-datatable) – 2014-03-27 00:36:51

回答

0

FastCsvReader on code-project做得非常好; IIRC它應該僅僅是:

var table = new DataTable(); 
using(var reader = new CsvReader(path)) { 
    table.Load(reader); 
} 

(但是這是從內存中)

0

微軟的論壇上有a thread about this,它使用CSV文件的數據連接字符串,這可能是最簡單/最快捷的方式。

或者,您可以一次讀取一行文件,併爲每行創建一個DataRow,並將其添加到DataTable中。這是更人工的工作,並可能需要您對文件(列數,列名稱,數據類型等)作出假設,但如果只是針對一個已知文件,那麼這應該不是一個大問題。

0

嘗試Filehelpers。它將幫助您將數據導入數據表以及強類型對象

+0

我也使用Filehelpers。 Filehelpers過去讓我的生活變得非常簡單。 – pavanred 2010-12-07 15:07:39

0

我已經在下面寫了五種方法將Csv文件轉換爲DataTable。

他們已經設計考慮到可選引號(例如,「符號),併成爲多才多藝儘可能不使用其他庫:

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

如果像我一樣,你從節省報告服務,那麼你應該使用這樣的:否則

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

,所有你需要做的是:

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) 

或者爲使用遠程存儲csv文件

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

    DataTable dt = GetDataTabletFromRemoteCsv(Url, IsHeadings)