Flutter: How to read data from simple spreadsheet?
Asked Answered
I

2

6

I am new to flutter and a have question that shouldn't be to hard to answer for a pro.

I have a simple spreadsheet with 5 columns and 10 rows. Now I have two variables, representing column and row index.

I want to simply read the corresponding value out of the spreadsheet, depending on the wanted column and row numbers.

Is this possible with flutter? Can flutter read a spreadsheet (.csv e.g.) and somehow get the information out of it?

I'm looking forward to an answer, thank you!

EDIT: This is the code I have so far, originally from https://flutter.io/cookbook/persistence/reading-writing-files/.

It prints

I/flutter (18817): Instance of 'Future'

but I don't know how to access the data.

Future<String> readTable() async {
    try {
      final file = File("assets/res/table.txt");

      // Read the file
      String contents = await file.readAsString();
      print(contents);
      return contents;
    } catch (e) {
      // If we encounter an error, return empty string
      return "";
    }
  }
Its answered 25/10, 2018 at 9:52 Comment(3)
Could you show the code you have tried so far?Perdomo
I updated my original question with the code I got so far. The problem is that I don't know how to access the data. Do you have an idea?Its
You need to use async/await where you call readTable() as well. There is no way to go back from async to sync.Admirable
I
15

Thanks for your answers. I made it work using async and await as can be seen in the following. Important as well is to declare the asset file in your pubspec.yaml like

flutter:
  assets:
    - assets/res/Book1.csv

Then declare both functions and just call loadCSV() when you want to load the data.

import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset(String path) async {
   return await rootBundle.loadString(path);
}

void loadCSV() {
  loadAsset('assets/res/Book1.csv').then((dynamic output) {
    csvRaw = output;
  });
}
Its answered 27/10, 2018 at 9:33 Comment(1)
how did you extract the data for a specified cell (using row & column number)? EDIT: I found pub.dev/packages/spreadsheet_decoder, will begin experimenting on it.Hazem
J
1

Tobi nailed the right answer, but to make that answer self-contained let me add here the need for:

import 'package:flutter/services.dart' show rootBundle;

to access rootBundle.

Jackstraws answered 9/4, 2021 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.