export method
Implementation
Future<bool> export({bool? raw}) async
{
// //////////
// EXCEL
// //////////
// List<int> excelBytes = await EXCEL.Excel.create(this.data);
// if (excelBytes != null) System().fileSaveAs(excelBytes, S.newId() + '.csv');
// ////////
// CSV
// ////////
List<int> csvBytes = []; // Our csvString is stored in Uint8List for output to file
// /////////////
// ALL DATA
// /////////////
// Note csvStringFromData() does not handle large amounts of data in chunks and can overflow
if (raw == true) {
String str = await csvStringFromData(this.data);
csvBytes = utf8.encode(str);
Platform.fileSaveAs(csvBytes, S.newId() + '.csv');
return true;
}
// /////////////
// GRID DATA
// /////////////
// HEADERS
GridItemModel? currItem;
int i = 0;
// String csvItems = '';
while ((currItem = getItemModel(i++)) != null) {
String csvCellText = '';
List<dynamic>? descendants = currItem!.findDescendantsOfExactType(TextModel);
if (descendants != null && descendants.isNotEmpty) {
descendants.forEach((val) {
var textLine = '';
// add return newline to csv for multiple text values within cell
// if (csvCellText != '') csvCellText += '\n';
textLine = val?.value ?? '';
// escape "'s in string
textLine.replaceAll('"', '""');
// surround in quotes for newline+returns / comma handling
textLine = (textLine.contains(',') || textLine.contains('\n')) ? '"' + textLine+ '"' : textLine;
// goto next column
csvCellText = textLine + ', ';
});
}
else {
csvCellText = '';
}
// go to next row
csvCellText += '\n';
// append the csv cell row to the csv string bytes
csvBytes = [...csvBytes, ...utf8.encode(csvCellText)];
// reset current csv row
csvCellText = '';
}
// eof replacing last \n with \r\n
if (csvBytes.length >= 2) {
csvBytes.removeLast(); // \ = 5c
csvBytes.removeLast(); // n = 6e
}
csvBytes = [...csvBytes, ...utf8.encode('\r\n')]; // \r\n = 5c, 72, 5c, 6e
// Uint8List.fromList(bytes) - typed_data conversion needed for converting back to Uint8List after manipulating the list
if ( csvBytes.isNotEmpty) Platform.fileSaveAs(Uint8List.fromList(csvBytes), S.newId() + '.csv');
return true;
}