Joe M
Joe M

Reputation: 107

Import a CSV file to my datagridview

I am working on a project where I have to import a CSV file, and display the results in a DataGridView. I am struggling to display my data fields to my datagridview, I want to be able add each row at a time so 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;

}

Upvotes: 3

Views: 16841

Answers (5)

Deniz
Deniz

Reputation: 456

Short and works, hope it helps

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

Upvotes: 0

code4life
code4life

Reputation: 15794

Why reinvent the wheel? FileHelpers is your friend.

Example of how to import a CSV to a DataTable is given here: http://www.filehelpers.net/docs/html/M_FileHelpers_CsvEngine_CsvToDataTable_2.htm

The static method signature under the relevant class (CsvEngine) is as easy as this:

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

Sweet, right?

Upvotes: 0

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16856

This is a class i use:

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

The separator in the file are ";", and the first row of the .csv file is the header names. If you what to change this check out 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;
    }
}

}

Upvotes: 0

Oscar Mederos
Oscar Mederos

Reputation: 29863

This is what I usually do:

  1. Define a class where each property represents a CSV column
  2. Use LINQToCSV (see here and here) to read the CSV file. It already gives me an IEnumerable<T> where T is my class.
  3. Populate the DataGridView as you usually do (either manually, through bindings, etc.)

An example of how to read a CSV file

Let's assume the CSV file has the columns Name, Last Name, Age

Then you do 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; }
}

Once you have it, you can read a list of Person from a CSV file like this:

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

Upvotes: 1

BeginnerCoder
BeginnerCoder

Reputation: 403

A CSV file is a normal text file that's just comma delimited.

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

Use these links. They should 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 some help writing the code.

Upvotes: 1

Related Questions