Reading CSV file and storing values into an array

后端 未结 19 1433
猫巷女王i
猫巷女王i 2020-11-22 06:35

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (\";\").

I am able

相关标签:
19条回答
  • 2020-11-22 06:53

    Just came across this library: https://github.com/JoshClose/CsvHelper

    Very intuitive and easy to use. Has a nuget package too which made is quick to implement: http://nuget.org/packages/CsvHelper/1.17.0. Also appears to be actively maintained which I like.

    Configuring it to use a semi-colon is easy: https://github.com/JoshClose/CsvHelper/wiki/Custom-Configurations

    0 讨论(0)
  • 2020-11-22 06:54

    I have been using csvreader.com(paid component) for years, and I have never had a problem. It is solid, small and fast, but you do have to pay for it. You can set the delimiter to whatever you like.

    using (CsvReader reader = new CsvReader(s) {
        reader.Settings.Delimiter = ';';
        reader.ReadHeaders();  // if headers on a line by themselves.  Makes reader.Headers[] available
        while (reader.ReadRecord())
            ... use reader.Values[col_i] ...
    }
    
    0 讨论(0)
  • 2020-11-22 06:58

    You can do it like this:

    using System.IO;
    
    static void Main(string[] args)
    {
        using(var reader = new StreamReader(@"C:\test.csv"))
        {
            List<string> listA = new List<string>();
            List<string> listB = new List<string>();
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(';');
    
                listA.Add(values[0]);
                listB.Add(values[1]);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:58

    The open-source Angara.Table library allows to load CSV into typed columns, so you can get the arrays from the columns. Each column can be indexed both by name or index. See http://predictionmachines.github.io/Angara.Table/saveload.html.

    The library follows RFC4180 for CSV; it enables type inference and multiline strings.

    Example:

    using System.Collections.Immutable;
    using Angara.Data;
    using Angara.Data.DelimitedFile;
    
    ...
    
    ReadSettings settings = new ReadSettings(Delimiter.Semicolon, false, true, null, null);
    Table table = Table.Load("data.csv", settings);
    ImmutableArray<double> a = table["double-column-name"].Rows.AsReal;
    
    for(int i = 0; i < a.Length; i++)
    {
        Console.WriteLine("{0}: {1}", i, a[i]);
    }
    

    You can see a column type using the type Column, e.g.

    Column c = table["double-column-name"];
    Console.WriteLine("Column {0} is double: {1}", c.Name, c.Rows.IsRealColumn);
    

    Since the library is focused on F#, you might need to add a reference to the FSharp.Core 4.4 assembly; click 'Add Reference' on the project and choose FSharp.Core 4.4 under "Assemblies" -> "Extensions".

    0 讨论(0)
  • 2020-11-22 07:00

    You can't create an array immediately because you need to know the number of rows from the beginning (and this would require to read the csv file twice)

    You can store values in two List<T> and then use them or convert into an array using List<T>.ToArray()

    Very simple example:

    var column1 = new List<string>();
    var column2 = new List<string>();
    using (var rd = new StreamReader("filename.csv"))
    {
        while (!rd.EndOfStream)
        {
            var splits = rd.ReadLine().Split(';');
            column1.Add(splits[0]);
            column2.Add(splits[1]);
        }
    }
    // print column1
    Console.WriteLine("Column 1:");
    foreach (var element in column1)
        Console.WriteLine(element);
    
    // print column2
    Console.WriteLine("Column 2:");
    foreach (var element in column2)
        Console.WriteLine(element);
    

    N.B.

    Please note that this is just a very simple example. Using string.Split does not account for cases where some records contain the separator ; inside it.
    For a safer approach, consider using some csv specific libraries like CsvHelper on nuget.

    0 讨论(0)
  • 2020-11-22 07:00

    I am just student working on my master's thesis, but this is the way I solved it and it worked well for me. First you select your file from directory (only in csv format) and then you put the data into the lists.

    List<float> t = new List<float>();
    List<float> SensorI = new List<float>();
    List<float> SensorII = new List<float>();
    List<float> SensorIII = new List<float>();
    using (OpenFileDialog dialog = new OpenFileDialog())
    {
        try
        {
            dialog.Filter = "csv files (*.csv)|*.csv";
            dialog.Multiselect = false;
            dialog.InitialDirectory = ".";
            dialog.Title = "Select file (only in csv format)";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var fs = File.ReadAllLines(dialog.FileName).Select(a => a.Split(';'));
                int counter = 0;
                foreach (var line in fs)
                {
                    counter++;
                    if (counter > 2)    // Skip first two headder lines
                    {
                        this.t.Add(float.Parse(line[0]));
                        this.SensorI.Add(float.Parse(line[1]));
                        this.SensorII.Add(float.Parse(line[2]));
                        this.SensorIII.Add(float.Parse(line[3]));
                    }
                }
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(
                "Error while opening the file.\n" + exc.Message, 
                this.Text, 
                MessageBoxButtons.OK, 
                MessageBoxIcon.Error
            );
        }
    }
    
    0 讨论(0)
提交回复
热议问题