Excel.fromCsv constructor

Excel.fromCsv(
  1. String csv, {
  2. String sheetName = 'Sheet1',
  3. bool inferTypes = true,
  4. CsvConfig? config,
  5. CsvSchema? schema,
})

Creates a new workbook from CSV csv, with the data in a single sheet.

The sheet is named sheetName (default 'Sheet1'). With inferTypes (the default) numeric and boolean fields are typed and guarded against silent data loss (a value such as 007 stays text); pass false to keep every field as text. config controls the delimiter and how the input is parsed (see CsvConfig, with presets like CsvConfig.excel and CsvConfig.tsv).

Pass a schema to force column types instead of inferring them: the first row is the header, and each named column is coerced to its declared type (see ExcelCsv.importCsv). A value that cannot be converted throws CsvParseException.

To add CSV to an existing workbook instead, use ExcelCsv.importCsv; to export, use SheetCsv.toCsv / ExcelCsv.toCsv.

final excel = Excel.fromCsv('name,age\nAlice,30', sheetName: 'People');
File('people.xlsx').writeAsBytesSync(excel.save()!);

Implementation

factory Excel.fromCsv(
  String csv, {
  String sheetName = 'Sheet1',
  bool inferTypes = true,
  CsvConfig? config,
  CsvSchema? schema,
}) {
  final excel = Excel.createExcel();
  final defaultName = excel.getDefaultSheet() ?? excel.sheetOrder.first;
  _fillSheetFromCsv(
    excel[defaultName],
    csv,
    inferTypes: inferTypes,
    config: config,
    schema: schema,
  );
  if (defaultName != sheetName) {
    excel.rename(defaultName, sheetName);
    excel.setDefaultSheet(sheetName);
  }
  return excel;
}