exportMothersToExcel static method

Future<void> exportMothersToExcel(
  1. BuildContext context,
  2. List<Document> documents
)

Implementation

static Future<void> exportMothersToExcel(
  BuildContext context,
  List<models.Document> documents,
) async {
  try {
    // Create a new Excel file and select the first sheet
    final excel = excelFactory();
    final Sheet sheet = excel['Sheet1'];

    // Add headers to the sheet
    sheet.appendRow(['Name', 'Organization', 'Device', 'Doctor', 'Test']);

    // Add data rows based on the documents provided
    for (var doc in documents) {
      final data = doc.data;

      sheet.appendRow([
        data['name'] ?? '',
        data['organizationName']?.toString() ?? '',
        data['deviceName']?.toString() ?? '',
        data['doctorName']?.toString() ?? '',
        data['noOfTests'] ?? '',
      ]);
    }

    // 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", "Mothers.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")));
  }
}