exportDoctorsToExcel static method

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

Implementation

static Future<void> exportDoctorsToExcel(
  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([
      'Name',
      'Email',
      'Organization',
      'Mother',
      'Test',
      'CreatedOn',
      'L.O.T',
      'Version',
    ]);

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

      sheet.appendRow([
        data['name'] ?? '',
        data['email']?.toString() ?? '',
        data['organizationName']?.toString() ?? '',
        data['noOfMother']?.toString() ?? '',
        data['noOfTests']?.toString() ?? '',
        data['createdOn'] ?? '',
        data['lastLoginTime'] ?? '',
        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", "Doctors.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")));
  }
}