0

I have a function that picks a XLSX file from phone storage. I want to use the selected file in another function to create a list.

This is MyData:

class MyData {
   MyData(this.time, this.value);
   final double time;
   final double value;
}

This is the function I use to select a file:

Future selectFile() async {
   final result = await FilePicker.platform.pickFiles(allowMultiple: false);

   if (result == null) return;
     final path = result.files.single.path!;

   setState(() => file = File(path));
}

Note: My xlsx file contains thousands of line so I will not share it here.

1 Answers1

0

A xlsx file is actually a zip file containing several xml files. You may use the excel library to get the content of a xlsx file. You should notice that you need version excel 2.0.0-null-safety or newer because we need null safety here.

Try this:

import 'dart:io';
import 'package:excel/excel.dart';

Future<List<MyData>> getListFromExcel(File file) async {
  Excel excelFile = Excel.decodeBytes(await file.readAsBytes());
  if (excelFile.sheets.isEmpty) {
    throw ArgumentError("Excel file has no sheets");
  }
  Sheet excelSheet = excelFile.sheets.values.first;
  return excelSheet.rows.map<MyData>((List<Data?> row) {
    if (row[0] == null || row[1] == null) {
      throw ArgumentError("Excel file contains empty cells");
    }
    else {
      return MyData(row[0]!.value.toString(), row[1]!.value.toString());
    }
  }).toList();
}
TripleNine
  • 1,457
  • 1
  • 4
  • 15
  • I had to update the question but not much has changed an I have a follow-up question: This time it is an xlsx file and I am getting an error when I try to use the list obtained from the function where I iterate through the values of the list. The error is this: FileSystemException: Failed to decode data using encoding 'utf-8' – Can Küçükyılmaz Sep 11 '22 at 19:28