Import CSV file into my datagridview

I am working on a project where I need to import a CSV file and display the results in a DataGridView. I am struggling to display my data fields in my datagridview, I want to add each row every time so that it parses them correctly. Here is my code so far.

   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;

}

      

+3


source to share


4 answers


CSV file is a regular text file separated by commas.

Basically what you want to do is open a text file and read each line and split by comma (",")

Use these links. They have to help. 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/

Let me know if you still need help writing the code.

+1


source


This is what I usually do:

  • Define a class where each property represents a CSV column
  • Use LINQToCSV

    (here here and here ) to read a file CSV. He already gives me IEnumerable<T>

    where T

    is my class.
  • Populate the DataGridView as usual (manually, using bindings, etc.).

An example of how to read a CSV file

Suppose CSV file has columns Name, Last Name, Age



Then you define the following class:

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

      

After that, you can read the list Person

from the CSV file, for example:

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

      

+1


source


This is the class I am using:

Call lCsv.ReadCsv ("your file path"), the method returns a datatable created from a .csv file.

The separator in the file is ";" and the first line of the .csv file is the header names. If you need to modify this lCsv.ReadCsv method

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

      

}

0


source


Why reinvent the wheel? FileHelpers

- your friend.

An example on how to import CSV into DataTable is given here: http://www.filehelpers.net/docs/html/M_FileHelpers_CsvEngine_CsvToDataTable_2.htm

The static method signature under the corresponding class ( CsvEngine

) is simple:

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

      

Sweet, right?

0


source







All Articles