开发者

Importing a CSV File that contains more than one value in a field

开发者 https://www.devze.com 2023-03-27 06:10 出处:网络
Here\'s the data I\'m trying to import from a CSV Time|Person|Products|Address (now)|person1|val1*val2*val3|adr1

Here's the data I'm trying to import from a CSV

Time|Person|Products|Address

(now)|person1|val1*val2*val3|adr1

where * is a linebreak/carriage return

here's what it looks like when I import it:

(now)|person1|val1val2val3开发者_StackOverflow|adr1 

Here's what I need it to look like:

(now)|person1|val1|adr1

(now)|person1|val2|adr1 etc.

I've tried: custom coding a CSV parser based mainly around string.Spilt(), it gave me the exact result and took forever to process. I've tried Sebastien Lorion's CSVReader and it gives me the exact same result, though it was markedly faster and easier to insert into my existing code. I've even tried the VB TextFieldParser with the exact same result.

Now, here's what I've thought about doing :

Somehow pass the field's values(I've no idea how to reference them) when I reach it to another method which returns a List<string> object through which I can iterate and add to a DataTable and from there do what needs doing. Remove my brain-stem with an old fork. Pace around muttering under my breath.

Here's the TextFieldParser code:

OpenFileDialog op = new OpenFileDialog();
op.ShowDialog();
TextFieldParser parser = new TextFieldParser(new StreamReader(op.FileName));
parser.SetDelimiters(",");

while (!parser.EndOfData)
{
    contents.AddRange(parser.ReadFields());
}


It would seem to me that if you have to stick with this CSV format, I would read it all in as you're doing above; but afterwards, I'd loop through your collection of data and then manually string split the products into the components that you need.

Trying to do it all in one pass is over complicating the issue.

Once you've got your separate classes you can then split the product on Carriage returns like so:

string[] result = input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);


Have a look at the FileHelpers library. It's very fast and quite flexible. Although I think you will have to write a little bit of custom processing logic for what you want to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号