Upload Excel File and Convert to Bar Chart

This solution performs an .xlsx file upload, then the data is converted into a Map/JSON. Finally, a JSON Path is used to filter the data and place it in the bar chart.

Expected Result (Run Mode)

Dependencies

The following steps will help you to do it:

1. Create a Custom Action.

// Automatic FlutterFlow imports
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

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

Future<dynamic> uploadExcelFile(Future<dynamic> Function() showSnackbar) async {
  // Add your function code here!
  try {
    // Open the file picker to allow the user to select an Excel
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xlsx'],
    );

    if (result == null) {
      // User canceled the picker
      return null;
    }

    // Read the selected Excel file
    var bytes = result.files.first.bytes!;
    var excel = Excel.decodeBytes(bytes);

    // Get the first sheet in the Excel file
    var sheet = excel.tables.keys.first;
    var rows = excel.tables[sheet]?.rows;

    List<Map<String, dynamic>> jsonData = [];

    for (var i = 1; i < rows!.length; i++) {
      Map<String, dynamic> rowMap = {};
      for (var j = 0; j < rows[i].length; j++) {
        // Get the header value for this column
        var header = rows[0][j]!.value.toString();

        // Get the cell value for this column
        var cellValue = (j == 1)
            ? double.parse(rows[i][j]!.value)
            : rows[i][j]!.value.toString();

        // Add the cell value to the row map using the header as the key
        rowMap[header] = cellValue;
      }
      jsonData.add(rowMap);
    }

    Map<String, dynamic> excelMap = {"data": jsonData};

    return excelMap;
  } catch (e) {
    showSnackbar();
    return null;
  }
}

Action Settings:

Code Notes:

The Snackbar ins't neccessary (shows a message if an error occurs) but you can follow this link Callback Action to do so.

The code only works with a static excel structure:

As you can see, A1 and B1 are the headers (keys for JSON) mentioned in the code, and the next rows will be the value. Example: {"Label" : "Week 3", "Value" : 40}

2. Add two State Variable.

3. Add a Button and set this Action flow.

The JSON Path for the Labels: $.data[*].Label

The JSON Path for the Values: $.data[*].Value

4. Add a Bar Chart and set the Chart Data.

Hope this helps you, any suggestions are welcome.

Have a nice time on FlutterFlow ๐Ÿ˜„!

7
10 replies