3

我正在做一个项目,我必须导入一个 CSV 文件,并在 DataGridView 中显示结果。我正在努力将我的数据字段显示到我的 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;

}
4

5 回答 5

1

这是我通常做的:

  1. 定义一个类,其中每个属性代表一个 CSV 列
  2. 使用LINQToCSV(参见此处此处)读取 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; }
}

拥有它后,您可以Person从 CSV 文件中读取列表,如下所示:

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);
}
于 2013-02-15T13:55:57.727 回答
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/

如果您仍然需要一些帮助来编写代码,请告诉我。

于 2013-02-15T13:49:59.797 回答
0

这是我使用的一个类:

调用 lCsv.ReadCsv("your file path"),该方法返回从 .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;
    }
}

}

于 2015-11-19T07:31:09.290 回答
0

为什么要重新发明轮子?FileHelpers是你的朋友。

此处给出了如何将 CSV 导入 DataTable 的示例: http ://www.filehelpers.net/docs/html/M_FileHelpers_CsvEngine_CsvToDataTable_2.htm

相关类 ( ) 下的静态方法签名CsvEngine就这么简单:

public static DataTable CsvToDataTable(
string filename,
string classname,
char delimiter
)

甜蜜,对吧?

于 2016-01-23T16:06:41.623 回答
0

简短而有效,希望对您有所帮助

    DataGridView my_dgvCSV = new DataGridView();
    DataTable my_dataTable = new DataTable();

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Size = new Size(750, 450);
        my_dgvCSV.Size = new Size(600, 400);
        my_dgvCSV.Location = new Point(5, 5);

        string[] raw_txt = File.ReadAllLines(@"D:\urPath\xyz.csv");
        string[] data_col = null;
        int x = 0;

        foreach (string txt_line in raw_txt)
        {
            data_col = txt_line.Split(';'); 
            // My .csv wanted (';') if it looks weird/wrong use (',')

            if (x == 0)
            {//header
                for (int i = 0; i <= data_col.Count() -1; i++)
                {
                    my_dataTable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {//data
                my_dataTable.Rows.Add(data_col);
            }
         }

         my_dgvCSV.DataSource = my_dataTable;
         this.Controls.Add(my_dgvCSV);
      }
于 2018-05-17T07:43:51.247 回答