How can I modify an Excel file and upload it to Firebase with Flutter?

I have two classes. One to download an Excel file from Firebase and another class that contains two functions. One to modify the file using an interface I have in another class. The second function is used to upload the file back to firebase. The problem is that the file should be used multiple times in the first function and I don't know how to do that. Thats my code:

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

class ExcelUtils {
  static Future<void> modifyAndStoreExcelFile(
    String filePath,
    String selectedProfessor,
    List<dynamic> monday,
    List<dynamic> tuesday,
    List<dynamic> wednesday,
    List<dynamic> thursday,
    List<dynamic> friday,
    List<dynamic> saturday,
  ) async {
    try {
      final bytes = await File(filePath).readAsBytes();
      final excel = Excel.decodeBytes(bytes);
      final sheet = excel['Feuil1'];
      for (var i = 6; i <= 39; i++) {
        var cellValue = sheet
            .cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: i))
            .value;
        if (cellValue == null) {
          print("cell value is null at row $i");
        } else {
          print("cell value is $cellValue at row $i");
        }
        if (cellValue.toString() == selectedProfessor) {
          sheet
                  .cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: i))
                  .value =
              monday[0].toString().replaceAll(RegExp(r'[^\w\s]+'), '\n');
        }
      }
      final modifiedFileBytes = excel.encode();
      await File(filePath).writeAsBytes(modifiedFileBytes!);
    } catch (e) {
      print('Error modifying and storing file: $e');
      throw e;
    }
  }

  static Future<void> uploadExcelFileToFirebase(String filePath) async {
    try {
      final modifiedFileBytes = await File(filePath).readAsBytes();
      final firebaseStorage = FirebaseStorage.instance;
      final firebaseStorageRef = firebaseStorage.ref();
      final firebaseStorageChildRef =
          firebaseStorageRef.child('modified_file.xlsx');
      await firebaseStorageChildRef.putData(modifiedFileBytes);
      await OpenFile.open(filePath);
    } catch (e) {
      print('Error uploading and opening file: $e');
      throw e;
    }
  }
}

I tried a lot of ways but nothing worked.



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)