Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Convert data from firestore into Excel sheet

How to convert data from Firestore Into an Excel sheet on both Android app and flutter web? Any response will be appreciated... thanks in advance!

like image 320
Jagadish Avatar asked Dec 08 '25 15:12

Jagadish


1 Answers

Excel library for flutter

You can go through the documentation here.

Now as jay asked to explain in detail how you are gonna retrive the data and store it in the excel sheet,

First step,

var excel = Excel.createExcel();           //create an excel sheet
Sheet sheetObject = excel['SheetName'];    //create an sheet object  

Second step, commands to write in excel sheet, where A is column id and 1 is row.

 var cell = sheetObject.cell(CellIndex.indexByString("A1"));
 cell.value = 8; // Insert value to selected cell;

Third step, getting data from firebase

QuerySnapshot _qs =
        await _notificationRef.where('language', isEqualTo: selectedLang).get(); // Lets say I have some collection where I need to get some documents with specific language

//This loop will iterate in all of the documents in the collection

for (int i = 0; i < _qs.docs.length; i++) {
 string data = _qs.docs[i].data()['names'];  //Where name is the field value in the document and i is the index of the document.
}  
});   

Now if we combine second and third step

QuerySnapshot _qs =
        await _notificationRef.where('language', isEqualTo: selectedLang).get(); 

for (int i = 0; i < _qs.docs.length; i++) {
 var cell = sheetObject.cell(CellIndex.indexByString('A${i+1}'));   //i+1 means when the loop iterates every time it will write values in new row, e.g A1, A2, ...
 cell.value =  _qs.docs[i].data()['names']; // Insert value to selected cell;
}  
});   

Once you are done with the data part you can save the file,

      // Save the Changes in file

      excel.encode().then((onValue) {
        File(join("Path_to_destination/excel.xlsx"))
        ..createSync(recursive: true)
        ..writeAsBytesSync(onValue);
    });

Once you are done with the saving you can choose any of the library to share your sheet to others,

Usually this libraries asks you to provide a file or file path which you can easily provide using the last code block explained where I passed file path to join method

like image 195
50_Seconds _Of_Coding Avatar answered Dec 11 '25 03:12

50_Seconds _Of_Coding