exportOrganizationsToExcel static method
Implementation
static Future<void> exportOrganizationsToExcel(
BuildContext context,
List<OrganizationDetailsModel> documents,
) async {
try {
// Create a new Excel file and select the first sheet
final excel = Excel.createExcel();
final Sheet sheet = excel['Sheet1'];
// Add headers to the sheet
sheet.appendRow([
'Name',
'Device',
'Doctors',
'Mother',
'Test',
'Mobile',
'Status',
'Created On',
'Address',
'Email',
]);
// Add data rows based on the documents provided
for (var doc in documents) {
final data = doc.organizations.first.data;
final address =
'${data['addressLine'] ?? ''}, ${data['city'] ?? ''}, ${data['state'] ?? ''}, ${data['country'] ?? ''}';
sheet.appendRow([
data['name'] ?? '',
doc.deviceCount ?? '',
doc.doctorCount ?? '',
doc.motherCount ?? '',
doc.testCount ?? '',
data['mobile'] ?? '',
data['status'] ?? '',
data['created_on'] ?? '',
address,
data['email'] ?? '',
]);
}
// Encode the Excel file and prepare it for download
final fileBytes = excel.encode();
final blob = html.Blob([fileBytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor =
html.AnchorElement(href: url)
..setAttribute("download", "organizations.xlsx")
..click(); // Trigger the download
html.Url.revokeObjectUrl(url); // Clean up the object URL after download
} catch (e) {
// Show an error message if the export fails
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text("Failed to export: $e")));
}
}