Giter Club home page Giter Club logo

csv's Introduction

Specify (at least a major) version when adding this project as dependency. Whenever the API has incompatible changes the major version changes!

Changes from version 3 to 4:

  • no new functionality.
  • adapted to dart2. This library is no longer a codec!

Changes from version 2 to 3:

  • parseNumbers has been renamed to shouldParseNumbers
  • FirstOccurenceSettingsDetector has been renamed to FirstOccurrenceSettingsDetector
  • Speed improvements.

Changes from version 3.0 to 3.1

  • added option delimitAllFields
  • fix issue #5 (endDelimiter was not always taken correctly from delimiter)

Changes from version 3.1 to 3.1.1

  • fix issue #10 (SDK version was overlay restrictive)

csv

A dart csv to list converter.

If you have a String of all rows with RFC conform separators and delimiters, simply convert them with:

List<List<dynamic>> rowsAsListOfValues = const CsvToListConverter().convert(yourString);

To convert to a Csv string your values must be in a List<List<dynamic>> representing a List of Rows where every Row is a List of values. You can then convert with:

String csv = const ListToCsvConverter().convert(yourListOfLists);

The default (RFC conform) configuration is:

  • , as field separator
  • " as text delimiter and
  • \r\n as eol.

See below if you need other settings, or want to autodetect them.

This converter may be used as transformer for streams:

final stream = Stream.fromIterable([['a', 'b'], [1, 2]]);
final csvRowStream = stream.transform(ListToCsvConverter());

Or the decoder side:

final input = File('a/csv/file.txt').openRead();
final fields = await input.transform(utf8.decoder).transform(CsvToListConverter()).toList();

The converter is highly customizable and even allows multiple characters as delimiters or separators.

Build Status

The decoder

Every csv row is converted to a list of values. Unquoted strings looking like numbers (integers and doubles) are by default converted to ints or doubles.

The encoder

The input must be a List of Lists. Every inner list is converted to one output csv row. The string representation of values is obtained by calling toString.

This converter follows the rules of rfc4180.

This means that text fields containing any delimiter or an eol are quoted.

The default configuration is:

  • , as field separator
  • " as text delimiter and
  • \r\n as eol.

This parser will accept eol and text-delimiters inside unquoted text and not throw an error.

In addition, this converter supports multiple characters for all delimiters and eol. Also, the start text delimiter and end text delimiter may be different. This means the following text can be parsed: «abc«d»*|*«xy»»z»*|*123
And (if configured correctly) will return ['abc«d', 'xy»z', 123]

Usage

Encoder List<List>String

If the default values are fine, simply instantiate ListToCsvConverter and call convert:

final res = const ListToCsvConverter().convert([[',b', 3.1, 42], ['n\n']]);
assert(res == '",b",3.1,42\r\n"n\n"');

Consider using the returnString = false option to work around a performance bug.

There are 2 interesting things to note:

  • Not all rows have to be the same length.
  • The default eol is '\r\n' and '\n' is also quoted. The appearance of only one character is enough for the string to be quoted.

The converter takes the following configurations either in the constructor or the convert function:

  • fieldDelimiter: the separator between fields. By default ',' but another common value is ';'.
  • textDelimiter: the quotation string. By default '"'.
  • textEndDelimiter: the end quotation string. By default, equals textDelimiter. The string used to end a quoted string.
  • eol: The new line string. By default '\r\n'. Another common value: '\n'
  • convertNullTo: If a value is null, use this value instead. To get an empty entry instead of string null, use ''.

All configuration values may be multiple characters!:

const conv = const ListToCsvConverter(fieldDelimiter: '|*|',
                                      textDelimiter: '<<',
                                      textEndDelimiter: '>>',
                                      eol: '**\n');
final res = conv.convert([['a','>'], ['<<', '>>'], [1, 2]]);
assert(res == 'a|*|<<>>>**\n<<<<>>|*|<<>>>>>>**\n1|*|2');

final res2 = const ListToCsvConverter()
    .convert([['a','>'], ['<<', '>>'], [1, 2]],
             fieldDelimiter: '|*|',
             textDelimiter: '<<',
             textEndDelimiter: '>>',
             eol: '**\n',
             convertNullTo: '');
assert(res == res2);

Note that:

  • '>' is quoted
  • '<<' is quoted as well, but because it is "only" a start text delimiter it is not doubled. (See rule 7. below).
  • '>>' is quoted. Only the end-quote string is doubled!

Decoder StringList<List>

If the default values are fine, simply instantiate CsvToListConverter and call convert:

final res = const CsvToListConverter().convert('",b",3.1,42\r\n"n\n"');
assert(res.toString() == [[',b', 3.1, 42], ['n\n']].toString());

Again please note that depending on the input not all rows have the same number of values.

The CsvToListConverter takes the same arguments as the ListToCsvConverter (except for convertNullTo) plus

  • shouldParseNumbers: by default true. If you want the output to be Strings only set this to false.

  • allowInvalid: by default true. The converter will by default never throw an exception. Even if fieldDelimiter, textDelimiter,... don't make sense or the csv-String is invalid. This may for instance happen if the csv-String ends with a quoted String without the end-quote (textEndDelimiter) string.

  • csvSettingsDetector: must be an object which extends from CsvSettingsDetector. There implementation simply selects the first occurrence of a list of possible values as value.

  • convertEmptyTo: If a field is empty (and not quoted!) use this value instead.
    convertEmptyTo: [1, 2, 3] would insert the list [1, 2, 3] whenever a field is empty.
    To convert empty fields to null, use the enum: EmptyValue.NULL: var csv = CsvToListConverter(convertEmptyTo: EmptyValue.NULL).convert(input);

    var d = FirstOccurrenceSettingsDetector(eols: ['\r\n', '\n'],
                                                textDelimiters: ['"', "'"]);
    
    CsvToListConverter(csvSettingsDetector: d);

In this case eol will either be '\r\n' or '\n' depending on which of those 2 comes first in the csv string. Note that the FirstOccurrenceSettingsDetector doesn't parse the csv string! For instance if eol should be '\r\n' but there is a field with a correctly quoted '\n' in the first row, '\n' is used instead.

If you csv String contains a (simple) header row, or all eols are equal this is good enough.

Feel free to submit something more intelligent.

To check your configuration values there is CsvToListConverter.verifySettings and verifyCurrentSettings. Both return an empty list if all settings are valid, or a list of errors. If the optional throwError is true an error is thrown in case the settings are invalid.

All settings must be set, i.e. not be null, and delimiters, separators and eols must be distinguishable, i.e. they may not be the start of another settings.

CSV rules -- copied from RFC4180 Chapter 2

Ad rule 3: removed as it is not relevant for this converter.

  1. Each record is located on a separate line, delimited by a line break (CRLF). For example: aaa,bbb,ccc CRLF zzz,yyy,xxx CRLF

  2. The last record in the file may or may not have an ending line break. For example: aaa,bbb,ccc CRLF zzz,yyy,xxx

  3. ... (Header-lines)

  4. Within the header and each record, there may be one or more fields, separated by commas. Each line should contain the same number of fields throughout the file. Spaces are considered part of a field and should not be ignored. The last field in the record must not be followed by a comma. For example:

    aaa,bbb,ccc

  5. Each field may or may not be enclosed in double quotes (however some programs, such as Microsoft Excel, do not use double quotes at all). If fields are not enclosed with double quotes, then double quotes may not appear inside the fields. For example:

    "aaa","bbb","ccc" CRLF zzz,yyy,xxx

  6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. For example:

    "aaa","b CRLF bb","ccc" CRLF zzz,yyy,xxx

  7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:

    "aaa","b""bb","ccc"

csv's People

Contributors

arnaudelub avatar boukeversteegh avatar close2 avatar darwingr avatar enyo avatar georgelesica-wf avatar glesica avatar ircecho avatar lil5 avatar nilsreichardt avatar usamasarwar avatar w2sv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

csv's Issues

RegEx field demilimter

Could it be possible to use RegEx field delimiters? I would like to use multiple tabs as delimiters.

Exclude header

Is there any way to exclude header from csv file while converting it into list?

No support sep paramter

Csv has an optional parameter at the header line.

For example

"sep=;"
a;b;
1;2;
3;4;

It is a csv which represents:

a b
1 2
3 4

But when i use the csv to parse it, i fould the result list which contain the first line "sep=;", and also the empty column will be included.

The result list will be:

list[0]=["sep=;"]
list[1]=["a","b",""]
list[2]=[1,2,""]
list[3]=[3,4,""]

Is there are any optional parameter to assign the sep parameter? I current use csv which version number is '5.0.2'.

problem with textDelimiter when converting to CSV

I'm trying to use csv-3.0.1 to parse some csv files. The conversion from CSV to List is ok, but I'm experiencing a strange behavior when converting a list to CSV. The problem is that the converter does not produce the text Delimiter, even though I try to force it. Here is one example:

Source

$ cat test.dart

import 'package:csv/csv.dart';

var csvStr = '''
"Alice","Austria",1
"Bob",",Brazil",2
''';

main() {
  var rowsAsLists = const CsvToListConverter(eol: '\n').convert(csvStr);
  print(rowsAsLists);
  var listsAsRows = const ListToCsvConverter().convert(rowsAsLists);
  print(listsAsRows);
  listsAsRows = const ListToCsvConverter().convert(rowsAsLists, textDelimiter: '#');
  print(listsAsRows);
}

Result

$ dart test.dart

[[Alice, Austria, 1], [Bob, ,Brazil, 2]]
Alice,Austria,1
Bob,",Brazil",2
Alice,Austria,1
Bob,#,Brazil",2

Look that the delimiter was shown when the string begins with the field separator.
I'm using...
Dart VM version: 1.14.0 (Thu Jan 28 09:20:03 2016) on "macos_x64"

Cant create more then 1 field per row

onPressed:  () async { 
                  //blocs.homePageBloc.onClickScheduleReview(); 
                  //Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => ScheduleReviewPage()));
                  
                    Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
                    bool isShown = await PermissionHandler().shouldShowRequestPermissionRationale(PermissionGroup.storage);
                    String appDocDir;
                    await getTemporaryDirectory().then((onValue) {
                      appDocDir = onValue.path;
                    });
                    final res = const ListToCsvConverter().convert([['aaa', ',', 'ccc'], ['barra n \n']]);
                    print(greenPen("[HomePage] tempDir: " + appDocDir));
                    File f = new File(appDocDir + "b.csv");
                    f.writeAsString(res);
                    blocs.providers.databaseProvider.uploadFile(f, 'csv', "c", "nnn");
                },

Is the output right? Tried to follow the official example.

image

Edit: solved by using ';' but still have a problem with ','

image

Edit: solved by using field delimiter ';'

image

Can't find the generated file

getCsv() async {
    String appDocDir = "";
    await getTemporaryDirectory().then((onValue) {
      appDocDir = onValue.path;
    });
    final res = const ListToCsvConverter().convert([
      ['aaa', ',', 'ccc'],
      ['barra n \n']
    ]);
    File f = new File(appDocDir + "b.csv");
    f.writeAsString(res);
  }

output:
I/flutter (13463): File: '/data/user/0/com.drodriguez.my_rents/cacheb.csv'

Screenshot_1634345446

Warning in cvs-5.1.0

After I upgraded to version 5.1.0 I get this warning message

/C:/Software/dart/hosted/pub.dev/csv-5.1.0/lib/src/csv_parser.dart:517:17: Warning: Operand of null-aware operation '!' has type 'bool' which excludes null.
    } else if (!quoted! && shouldParseNumbers) {
                ^

Not sure if you are aware of it.

Thanks,
T

poor performance when reading large csv files

Hi,

Thanks for providing this package. I've tried to read in a large csv file 165,000 rows, 20 colums about 30 MB of data. It took more than 1 min to convert the file into a List<List>.

Stopwatch stopwatch = new Stopwatch()..start();
var str = new File("testfile.csv").readAsStringSync(); // the read part is very fast
List<List> aux = const CsvToListConverter(eol: "\n").convert(str);
print("Took ${stopwatch.elapsed} to read csv file");

This is with Dart 1.8.5.

For comparison, R reads the data into a data.frame in less than 5 seconds.

Is there anything that can be done to speed up the Dart implementation?

Thanks,
Tony

Overly restrictive SDK dependency

Because the Dart SDK's current version is 1.16.1, your project's dependency in this area is preventing me from including the CSV package.

Dart 1.17.1 pub get not finding csv: 3.0.1

I ran a fresh pub get using Dart 1.17.1 and it can't find csv 3.0.1

$ dart --version
Dart VM version: 1.17.1 (Fri Jun 10 04:46:03 2016) on "macos_x64"

$ cat pubspec.yaml 
name: "enchilada"
dependencies:
  browser: "^0.10.0+2"
  csv: ^3.0.1

$ pub get
Resolving dependencies... 
Package csv has no versions that match >=3.0.1 <4.0.0 derived from:
- enchilada depends on version ^3.0.1

Mime type

Generated csv is not recognized as csv mime type

Escaping

I haven't found an option to set the escape character, is there any option planned for this ? I'm trying to convert my apache CSV code, which supports a few more options for custom formats in the wild.

Dart 2 runtime errors

I think this is related to #15 . When tests are run with dart --preview-dart-2 (with a recent dev build of Dart, like at least 2.0.0-dev.50.0), we get some runtime errors. Here are some examples:

$ dart --preview-dart-2 test/list_to_csv_test.dart
...
00:00 +11 -1: Works as transformer [E]
  type '_GeneratedStreamImpl<List<dynamic>>' is not a subtype of type 'Stream<List<List<dynamic>>>' of 'stream' where
    _GeneratedStreamImpl is from dart:async
    List is from dart:core
    Stream is from dart:async
    List is from dart:core
    List is from dart:core

  dart:convert/converter.dart                                   Converter.bind
  dart:async/stream.dart 630:30                                 Stream.transform
  test/list_to_csv_test.dart 186:28                             main.<fn>
...
00:00 +11 -1: Issue 5. Quote correctly
00:00 +12 -1: Issue 7.  Test delimitAllFields
00:00 +13 -1: Some tests failed.

Also

$ dart --preview-dart-2 test/csv_to_list_test.dart
...
00:00 +21 -7: Transformer autodetects settings for a multiline csv correctly [E]
  type 'List<dynamic>' is not a subtype of type 'List<List<dynamic>>' of 'data' where
    List is from dart:core
    List is from dart:core
    List is from dart:core

  dart:async/stream_transformers.dart                           _EventSinkWrapper.add
  lib/csv_to_list_converter.dart 242:18                         CsvToListSink._add
  lib/csv_to_list_converter.dart 251:5                          CsvToListSink.ad
...
00:00 +21 -7: Argument verification works
00:00 +22 -7: Some tests failed.

The numbers or time contain "\"

Hi There,
Thank you for the package.
I tried to parse some csv file, but looks like there are something not working well.The numbers or timedate are deliminated with "":

image

the code:

 // Read the file
    final strFile = await file.readAsString(
      encoding: systemEncoding,
    );
   
    List<List<dynamic>> listLines = const CsvToListConverter(
      eol: "\n",
      fieldDelimiter: ",",
      shouldParseNumbers: false,
    ).convert(strFile);

The data in csv file:

"Measurement position,,,50,150"
"Time stamp,2014-05-15,,14:21:25,14:21:25"

Thank you.

Delimiter for decimal

Is there a way to specify the delimiter for decimal number? for example:

1.23
or
1,23

Thanks

[bug] `CsvToListConverter` does not split last row element from the first element of the next row.

Tested with this code:

import 'dart:io';
import 'dart:convert' show utf8;
import 'package:csv/csv.dart';

final csvFilePath = './addresses.csv';

void main(List<String> arguments) async {
  final input = File(csvFilePath).openRead();
  final raw = await input
      .transform(utf8.decoder)
      .transform(CsvToListConverter())
      .toList();
  print(raw);
}

and this dataset: "addresses.csv"

John,Doe,120 jefferson st.,Riverside, NJ, 08075
Jack,McGinnis,220 hobo Av.,Phila, PA,09119
"John ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075

In the console output you can see that "08075
Jack" are the same element in the resulting List

[[John, Doe, 120 jefferson st., Riverside,  NJ,  08075
Jack, McGinnis, 220 hobo Av., Phila,  PA, 09119
John Da Man, Repici, 120 Jefferson St., Riverside,  NJ, 8075]]

And the same as in the issue #49. All rows are a single element of the resulting List

ListToCSVConverter generates extra CR for new line

Error in CSV:4.0.3

ListToCSVConverter generate an extra CR code for each new line.

The method convert(), generates one CR + CR + LF at the end of each line, when only one LF or one CR+LF pair is expected.

ErrorCSV

svToListConverter().convert doesn`t work on IOS (works on android)

I have a csv on this format with 28 lines:

id,name,image
familia,Família,familia.jpg
minhafamilia,Minha Família,minha-familia.jpg
escola,Escola,escola.jpg
sentimentos,Sentimentos,sentimentos.jpg

On android it creates a list of 28 itens, each one with 3 itens, just as the csv.

On IOs it creates a list of 61 itens, ignoring the first field and adding the 2nd and 3rd field on a sequence. Weird. I`m 3 hours here trying to find out what the problem was.

my code:

     final String categoriesCsvContent = await rootBundle.loadString('assets/csvs/$categoriesCsvFileName');
    _categoriesCsvData = CsvToListConverter().convert(categoriesCsvContent);

I got the problem just now, it is the eol, so I just changed like this:

    categoriesCsvContent = await rootBundle.loadString('assets/csvs/$categoriesCsvFileName');
    categoriesCsvContent = categoriesCsvContent.replaceAll('\n','\r\n');

But it would be nice if the code could treat this automatically.

please increase sdk version in pubspec

The current Dart SDK version is 2.1.0.

Because csv 4.0.0 requires SDK version >=2.0.0-dev.0.0 <2.1.0 and no versions of csv match >4.0.0 <5.0.0, csv ^4.0.0 is forbidden.

utf-8 support?

Hi! Does the library supports UTF-8 characters? I tried to create a .csv-file with cyrillic symbols without success.

Not working on iOS

using csv: ^4.0.3

I have successfully converted a csv file on Andoid, but the same code doesn't work on iOS.

String codetxt = await rootBundle.loadString('assets/file.csv');
List<List<dynamic>> codeList = CsvToListConverter().convert(codetxt);
print('codelist size ' + codeList.length.toString());

This results in 66k entries for Android, but only 1 for iOS.

I've checked that the csv is loading properly on iOS. I'm not sure what else I should be looking for to track down the cause?

Safari issue in exported csv

I am using this library to generate the csv from array list in flutter web

When there is chrome works fine.
But in safari it gives me the csv data but not in different raw but in all the records in single row

If anyone has solution please provide

Thanks in advance

Encoding strings

First of all, thanks for the library, very helpful.

I'm writing string values, and I even have them typed as such, but the library is deciding when to quote them, this is causing a string value of "1973" to be attempted to read as a number which fails as I'm trying to read it as a string again. So, right not I can't read the same file the library wrote.

Let me know if I'm using it incorrectly, my current workaround is to tell it to not decode any numbers, but that doesn't let me have numeric columns.

I'd appreciate it if I could tell the encoder to always encode strings with quotes, and leave numeric types w/o quotes. Barring that, the next best thing would be to specify on encode/decode how to encode each column.

Decoding and encoding CSV is extremely slow

This is only noticeable with large datasets but once you have anything resembling a non-trivial CSV file, this package takes absurd amounts of time to decode or encode the files.

Create sheet

How can I create another sheet for the same file?

Unexpected Error: The text end delimiter (") for the last field is missing.

Trying to parse a CSV file that ends with " but without the hidden EOL char like \r\n after ", it will result in an error: The text end delimiter (") for the last field is missing..

It seems related to the _insideQuotedString flag maintenance during the parse, which will be reset only when

  1. a new field delimiter appeared,
  2. a new EOL appeared

after it was set to true.

The issue here does not meet these two conditions and the flag stays true to parse closing and leads to the error.

csv 3.2.0 doesn't work with dart 1.24.3

'package:csv/csv_to_list_converter.dart': malformed type: line 8 pos 34: cannot resolve class 'StreamTransformerBase' from 'CsvToListConverter'
class CsvToListConverter extends StreamTransformerBase<String, List>

treatment of null

Hi,

Would you consider adding another parameter to ListToCsvConverter that will customize how nulls get treated? Currently, for [1, null, 3] you get 1,null,3. That is inconvenient if you import the output into a spreadsheet program as the nulls will stick out. I would prefer the ability to convert the nulls to empty strings or maybe something else. Of course, I can preprocess my data, but that requires another pass.

What do you think?

Thanks,
Tony

add option to add delimiters to all fields

RFC says, that we don't need to quote any text, which doesn't contain any "special" characters (delimiters, separator, eol).

Add an options to nevertheless quote everything.

This issue has been extracted from issue #5.

EOL error

image
I had this error using csv parse. EOL not being identified.

Parse csv content is not correct

Hi,
Thank you for your hardword to make a great lib.

Currently, I found an issue with following csv content:

"A B", "C, D"

I think the result should be two fields: A B & C, D.
But actually, the lib parse result as three fields: A B, C and D;


Here is my sample code:

import 'package:csv/csv.dart';

void main() {
  final rows = const CsvToListConverter().convert('"A B", "C, D"\r\n');
  for (final row in rows) {
    print(row.join('_ '));
  }
}

Output

A B_  C_  D

Analysis error with latest Dart SDK 1.22

This library does not seem to be compatible with Dart 1.22. It prevents a pub build in a project depending on it with analyzer errors.

It seems that extending Converter and implementing StreamTransformer is the problem. Removing the implements StreamTransformer in both list_to_csv_converter.dart and csv_to_list_converter.dart seem to resolve the issue since a Converter already implements StreamTransformer.

abstract class Converter<S, T> implements StreamTransformer<S, T> {
class ListToCsvConverter extends Converter<List<List>, String>
    implements StreamTransformer {

Analysis Errors:

➜  csv git:(master) ✗ dartanalyzer lib
Analyzing [lib]...
[error] Inconsistent declarations of 'bind' are inherited from (Stream<String>) → Stream<List<List<dynamic>>>, (Stream<dynamic>) → Stream<dynamic>. (/Users/robbecker/code/csv/lib/csv_to_list_converter.dart, line 8, col 7)
[error] Base class introduces an invalid override. The type of 'Converter.bind' ('(Stream<String>) → Stream<List<List<dynamic>>>') isn't a subtype of 'StreamTransformer<dynamic, dynamic>.bind' ('(Stream<dynamic>) → Stream<dynamic>'). (/Users/robbecker/code/csv/lib/csv_to_list_converter.dart, line 8, col 26)
[error] Inconsistent declarations of 'bind' are inherited from (Stream<List<List<dynamic>>>) → Stream<String>, (Stream<dynamic>) → Stream<dynamic>. (/Users/robbecker/code/csv/lib/list_to_csv_converter.dart, line 74, col 7)
[error] Base class introduces an invalid override. The type of 'Converter.bind' ('(Stream<List<List<dynamic>>>) → Stream<String>') isn't a subtype of 'StreamTransformer<dynamic, dynamic>.bind' ('(Stream<dynamic>) → Stream<dynamic>'). (/Users/robbecker/code/csv/lib/list_to_csv_converter.dart, line 74, col 26)
[error] Invalid override. The type of 'ListToCsvConverter.startChunkedConversion' ('(Sink<dynamic>) → List2CsvSink') isn't a subtype of 'Converter<List<List<dynamic>>, String>.startChunkedConversion' ('(Sink<String>) → Sink<List<List<dynamic>>>'). (/Users/robbecker/code/csv/lib/list_to_csv_converter.dart, line 173, col 3)
5 errors found.

image

image

Different output in debug and when deployed

Screenshot_2
Screenshot_4
So I was testing CSV documents in flutter and when debugging I get a List of Lists (a list for each row) as you can see in the attachment, but when deploying I get a different result: A List of a List with every cell value (also attached).
My code:
Future<void> loadCSV() async { final _rawData = await rootBundle.loadString("assets/test.csv"); List<List<dynamic>> listData = const CsvToListConverter().convert(_rawData); js.context.callMethod("alert", <String>["listData $listData"]); }
Build command:
if cd flutter; then git pull && cd ..; else git clone https://github.com/flutter/flutter.git; fi && flutter/bin/flutter config --enable-web && flutter/bin/flutter build web --release

[Feature request] Support for parsing the header

The current API of accesing fields values is:

List<List<dynamic>> rows = const CsvToListConverter(
      eol: '\n',
      shouldParseNumbers: false,
    ).convert(fileContents);

// Row zero has the headers; discard it.
String idColumnValue = rows[1][0];

Which works if the file columns are guranteed to be in a static order.

It would be great if we could access columns values by their name:

List<List<dynamic>> rows = const CsvToListConverter(
      eol: '\n',
      shouldParseNumbers: false,
      parseHeaders: true, // New config option
    ).convert(fileContents);

// Row zero had headers but was parsed and dropped.
String idColumnValue = rows[0]["id"];

Csv content cannot display Traditional Chinese if open in Excel

hi , I am using csv 5.0.0 plugin, and try to export the csv file which contains Traditional Chinese to Flutter Web. After export the file , using notepad open the file is OK, however open in Excel the content will become (???????? ) . Can you help with this? Thanks

Sample Code as below:

`
import 'package:csv/csv.dart';

String fileName = "testFile.csv";
List<List> wholeFile = new List<List>();
wholeFile.add(["姓", "名", "性別"]);
wholeFile.add(["陳", "大文", "男"]);
String csvString = ListToCsvConverter().convert(wholeFile);
new html.AnchorElement(href: "data:text/plain;charset=utf-8,$csvString")
..setAttribute("download", "$fileName")
..click();
`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.