Rajesh
Rajesh

Reputation:

What is best way to read CSV data?

I am using C# and trying to read a CSV by using this connection string;

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\rajesh.yadava\Desktop\orcad;Extended  Properties="Text;HDR=YES;IMEX=1;FMT=Delimited"

This works for tab delimited data.

I want a connection string which should for tab delimited as well as comma(,) and pipe(|).

How can I make a generic connection string for CSV.

Thanks Rajesh

Upvotes: 1

Views: 2296

Answers (7)

geryjuhasz
geryjuhasz

Reputation: 184

    class CSVFile extends SplFileObject
{

private $keys;

    public function __construct($file)
    {
        parent::__construct($file);
        $this->setFlags(SplFileObject::READ_CSV);
    }

    public function rewind()
    {
        parent::rewind();
        $this->keys = parent::current();
        parent::next();
    }

    public function current()
    {
        return array_combine($this->keys, parent::current());
    }

    public function getKeys()
    {
        return $this->keys;
    }
}

then use with:

$csv = new CSVFile('exmaple.csv');

and you can iterate through lines using:

foreach ($csv as $line)
{

Upvotes: 0

JeffH
JeffH

Reputation: 10482

Without rolling a custom solution, I'm not sure there's a straightforward way to support more than one delimiter. This page suggests that through schema.ini you can choose between:

  • TabDelimited
  • CSVDelimited
  • one specific character (except double quote)
  • fixed width

Upvotes: 0

Reputation:

Is using the TextFieldParser class an option?

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx

Upvotes: 0

hangy
hangy

Reputation: 10859

In case that you need a fast sequential access to the CSV file, the Fast CSV Reader could be an option. I have used it on a project some time ago with great success. It is supposed to be optimized quite well and also provides a cached version, if you need it. Additionally, it was updated several times since it was first released back in 2005 (last update in 2008-10-09) and it supports basic databinding by implementing System.Data.IDataReader.

Upvotes: 1

bugmagnet
bugmagnet

Reputation: 7769

Here's a few links from the net discussing this issue:

Upvotes: 0

Nick Randell
Nick Randell

Reputation: 18295

I know this doesn't answer your questions, but here's a word of warning.

I've had to create my own reader as you don't get the correct drivers if you ever run on a 64 bit system.

If your software will ever run on a 64 bit system, make sure you test it first and that the oledb or odbc drivers will be present.

Upvotes: 1

bob
bob

Reputation: 6485

Is the filehelpers library an option?

Upvotes: 2

Related Questions