readExcelAsDatacat static method

Future<Datacat> readExcelAsDatacat(
  1. String path
)

Reads an Excel file and returns a Datacat for the first sheet.

Requires the 'excel' package.

Implementation

static Future<Datacat> readExcelAsDatacat(String path) async {
  final bytes = await File(path).readAsBytes();
  final excel = Excel.decodeBytes(bytes);
  final sheetName = excel.tables.keys.first;
  final sheet = excel.tables[sheetName]!;
  if (sheet.maxRows == 0) return Datacat(columns: [], rows: []);
  // Assume the first row contains column headers.
  final columns =
      sheet.row(0).map((cell) => cell?.value?.toString() ?? '').toList();
  final dataRows = <List<dynamic>>[];
  for (int i = 1; i < sheet.maxRows; i++) {
    final row = sheet.row(i).map((cell) => cell?.value).toList();
    dataRows.add(row);
  }
  return Datacat(columns: columns, rows: dataRows);
}