exportDevicesToExcel static method
- BuildContext context,
- List<
Document> documents
Exports the given list of device documents
to an Excel file and triggers a download in the browser.
This method creates a new Excel file, adds headers and device data rows, and then
initiates a download of the generated .xlsx
file for the user. If an error occurs,
a snackbar with an error message is shown using the provided context
.
context
: The BuildContext used to show error messages.
documents
: The list of Appwrite Document objects containing device data to export.
Implementation
static Future<void> exportDevicesToExcel(
BuildContext context,
List<models.Document> 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([
'Doppler Number',
'Device Code',
'Organization',
'Mother',
'Test',
'CreatedOn',
'Version',
]);
// Add data rows based on the documents provided
for (var doc in documents) {
final data = doc.data;
sheet.appendRow([
data['deviceName'] ?? '',
data['deviceCode']?.toString() ?? '',
data['organizationName']?.toString() ?? '',
data['noOfMother']?.toString() ?? '',
data['noOfTests']?.toString() ?? '',
data['createdOn'] ?? '',
data['appVersion'] ?? '',
]);
}
// 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", "Devices.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")));
}
}