2013-02-15 114 views
3

我正在处理一个项目,我必须导入CSV文件并在DataGridView中显示结果。我努力将我的数据字段显示到我的datagridview,我希望能够一次添加每行,以便正确解析它们。这是我的代码到目前为止。将CSV文件导入到我的datagridview

csv.MissingFieldAction = MissingFieldAction.ReplaceByNull; 
    int fieldCount = csv.FieldCount; 
    string[] headers = csv.GetFieldHeaders(); 
    fieldCount = fieldCount - 1; 

    //TO DO: Reading Header Information 

    for (int i = 0; i <= fieldCount; i++) 
    { 
     DataGridViewTextBoxColumn headerRow = new DataGridViewTextBoxColumn(); 
     headerRow.Name = headers[i]; 
     headerRow.HeaderText = headers[i]; 
     headerRow.Width = 100; 
     dgvComplianceImport.Columns.Add(headerRow); 
    } 


    while (csv.ReadNextRecord()) 
    { 
     //for (int i = 0; i < fieldCount; i++) 
     // string.Format("{0} = {1};", 
     //     headers[i], 
     //     csv[i] == null ? "MISSING" : csv[i]); 



     //TO DO: for loop to add each data field row 

     DataGridViewRow dgvr = new DataGridViewRow(); 
     for (int fieldCount = 0; fieldCount <= csv.FieldCount; fieldCount++) 
     { 
      string field = csv[fieldCount]; 


     } 
     dgvr.Cells.Add(new DataGridViewCell()); 
     dgvComplianceImport.Rows.Add(dgvr); 
    } 

    dgvComplianceImport.DataSource = csv; 

} 
+0

嗨!欢迎来到Stackoverflow!你有问题吗?你为什么挣扎?它在做什么? – 2013-02-15 13:45:45

+0

你到底在干什么? – 2013-02-15 13:48:39

+0

什么类型是'csv'? – ja72 2013-02-15 14:00:56

回答

1

CSV文件是一个正常的文本文件,只是逗号分隔。

基本上你想要做的就是打开文本文件,并通过每行读取和逗号分割(“”)

使用这些链接。他们应该帮忙。 http://www.codeproject.com/Articles/16951/Populating-data-from-a-CSV-file-to-a-DataGridView

http://www.c-sharpcorner.com/uploadfile/ankurmee/import-data-from-text-and-csv-file-to-datagridview-in-net/

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/9efdbbd7-bfd9-4c7f-9198-791a4ca88a44/

让我知道,如果你还需要一些帮助编写代码。

+0

嗨感谢您的回复。麻烦的是我不想用逗号溢出它,因为csv文件可能包含带逗号的单元格。所以我使用这个链接来解析CSV文件:http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader#latup。然而,它并没有完全按照我计划的方式工作,因为当我在datagridview中显示结果时,它不允许我编辑它,我需要能够编辑dgv并重新保存它。 – 2013-02-15 13:59:30

+0

为了防止出现这种情况,我试图让它不这样做,我需要循环遍历CSV文件中的每个数据行,并将每行添加到dgv。对不起,如果这有点混乱。 – 2013-02-15 14:00:17

+0

你能告诉我你在哪里得到CSV文件吗?您是否从您编写的另一个应用程序生成它?或者它是一些其他的应用程序? – BeginnerCoder 2013-02-15 14:03:24

1

这是我平时做:

  1. 定义一个类,其中每个属性代表一个CSV列
  2. 使用LINQToCSV(见herehere)来读取CSV文件。它已经给我一个IEnumerable<T>,其中T是我的课。
  3. 填充DataGridView中,你通常会做(手动,通过绑定等)

如何阅读的例子的CSV文件

让我们假设CSV文件中的列Name, Last Name, Age

那么你就定义了以下类:

class Person { 
    [CsvColumn(FieldIndex = 0, CanBeNull = false, Name = "Name")] 
    public string Name { get; set; } 
    [CsvColumn(FieldIndex = 1, CanBeNull = true, Name = "Last Name")] 
    public string Last Name { get; set; } 
    [CsvColumn(FieldIndex = 2, CanBeNull = true, Name = "Age")] 
    public int Age { get; set; } 
} 

一旦你拥有了它,你可以从一个CSV文件这样读的Person列表:

public IEnumerable<Person> ReadFromCsv(string csvFile) { 
    //Here you set some properties. Check the documentation. 
    var csvFileDescription = new CsvFileDescription 
    { 
     FirstLineHasColumnNames = true, 
     SeparatorChar = ',' //Specify the separator character. 
    }; 

    var csvContext = new CsvContext(); 

    return csvContext.Read<Person>(csvFile, csvFileDescription); 
} 
+0

@JoeMarsden测试它,让我们知道它是如何去的 – 2013-02-15 14:42:44

0

这是一类使用:

呼叫lCsv.ReadCsv(“你的文件路径”),该方法返回一个从.csv文件创建的数据表。

文件中的分隔符是“;”,.csv文件的第一行是标头名称。如果你有什么要改变这种检查方法lCsv.ReadCsv

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Text; 
using System.Data; 

namespace ReadWriteCsv 
{ 
/// <summary> 
/// Class to store one CSV row 
/// </summary> 
public class CsvRow : List<string> 
{ 
    public string LineText { get; set; } 
} 

/// <summary> 
/// Class to read data from a CSV file 
/// </summary> 
public class CsvFileReader : StreamReader 
{ 
    public CsvFileReader(Stream stream) 
     : base(stream) 
    { 
    } 

    public CsvFileReader(string filename) 
     : base(filename) 
    { 
    } 

    /// <summary> 
    /// Reads a row of data from a CSV file 
    /// </summary> 
    /// <param name="row"></param> 
    /// <returns></returns> 
    public bool ReadRow(CsvRow row) 
    { 
     row.LineText = ReadLine(); 
     if (String.IsNullOrEmpty(row.LineText)) 
      return false; 

     int pos = 0; 
     int rows = 0; 

     while (pos < row.LineText.Length) 
     { 
      string value; 

      // Special handling for quoted field 
      if (row.LineText[pos] == '"') 
      { 
       // Skip initial quote 
       pos++; 

       // Parse quoted value 
       int start = pos; 
       while (pos < row.LineText.Length) 
       { 
        // Test for quote character 
        if (row.LineText[pos] == '"') 
        { 
         // Found one 
         pos++; 

         // If two quotes together, keep one 
         // Otherwise, indicates end of value 
         if (pos >= row.LineText.Length || row.LineText[pos] != '"') 
         { 
          pos--; 
          break; 
         } 
        } 
        pos++; 
       } 
       value = row.LineText.Substring(start, pos - start); 
       value = value.Replace("\"\"", "\""); 
      } 
      else 
      { 
       // Parse unquoted value 
       int start = pos; 
       while (pos < row.LineText.Length /*&& row.LineText[pos] != ','*/) 
        pos++; 
       value = row.LineText.Substring(start, pos - start); 

      } 

      // Add field to list 
      if (rows < row.Count) 
       row[rows] = value; 
      else 
       row.Add(value); 
      rows++; 

      // Eat up to and including next comma 
      while (pos < row.LineText.Length /*&& row.LineText[pos] != ','*/) 
       pos++; 
      if (pos < row.LineText.Length) 
       pos++; 
     } 
     // Delete any unused items 
     while (row.Count > rows) 
      row.RemoveAt(rows); 

     // Return true if any columns read 
     return (row.Count > 0); 
    } 
} 

public class lCsv 
{ 
    public static DataTable ReadCsv(string sPath) 
    { 
     DataTable dtIssues = new DataTable(); 
     int iRowCount = 0; 
     int iColumnCount = 0; 
     // Read sample data from CSV file 
     using (CsvFileReader reader = new CsvFileReader(sPath)) 
     { 
      CsvRow row = new CsvRow(); 
      while (reader.ReadRow(row)) 
      { 
       foreach (string fullrow in row) 
       { 
        if (iRowCount == 0) 
        { 
         foreach (string sName in fullrow.Split(';')) 
         { 
          dtIssues.Columns.Add(sName); 
          iColumnCount++; 
         } 
         iRowCount++; 
        } 
        else 
        { 
         DataRow drIssue = dtIssues.NewRow(); 
         int iAddCount = 0; 
         foreach (string sName in fullrow.Split(';')) 
         { 
          if (iAddCount < iColumnCount) 
          { 
           drIssue[iAddCount] = sName; 
           iAddCount++; 
          } 
         } 

         dtIssues.Rows.Add(drIssue); 
        } 
       } 
      } 
     } 

     return dtIssues; 
    } 
} 

}