flutterdartexport-to-excel

Insert Images into an Excel File (Flutter Framework)


Excel

I am using the excel package to create an Excel file. My problem is that I can't insert images into an Excel file. How can I insert images or any type of binary data?

My excel file contains 4 columns :

I developed code to export an Excel file.

void startExportCategoriesExcel(List<ExportParams> ExportParams,
      CustomerModel customerModel, String accountBase64, bool share) async {
    if (ExportParams.isEmpty) {
      showToast(Trans.noDataToExport.trans());
      return;
    }

    try {
      showLoadingProgressAlert();

      final String sheetName = "Category-PAR-${Random().nextInt(10000)}";
      final excel = Excel.createExcel();
      excel.rename('Sheet1', sheetName);
      final Sheet sheetObject = excel[sheetName];

      List<List<dynamic>> excelExport = [];
      // excelExport = [
      //   [customerModel.customerName,
      //   customerModel.phoneNo ?? '',
      //   ]
      // ];

      excelExport.add([
        "#",
        Trans.image.trans(),
        Trans.name.trans(),
        Trans.uom.trans(),
        Trans.price.trans(),
        Trans.barcode.trans(),
      ]);

      int index = 0;
      for (var element in ExportParams) {
        index++;

        // Load the image from the network using http package
        img.Image? image;
        try {
          var response = await Dio().get(element.image,
              options: Options(responseType: ResponseType.bytes));
          if (response.statusCode != 200) {
            logger('Failed to load image: ${response.statusCode}');
          }

          image = img.decodeImage(Uint8List.fromList(response.data));
        } catch (e) {
          image = null;
        }

        final barcodeImage = img.Image(width: 300, height: 50);
        img.fill(barcodeImage, color: img.ColorRgb8(255, 255, 255));
        drawBarcode(
          barcodeImage,
          Barcode.code128(),
          element.barcode ?? "",
        );

        // var excelImage = ExcelImage(image);

        excelExport.add([
          "$index",
          image != null
              ? image.buffer.asUint8List()
              : image ?? '', //element.image,
          element.name,
          element.prices.isEmpty ? '-' : element.prices.first.uom,
          element.prices.isEmpty ? '-' : element.prices.first.price,
          barcodeImage.buffer.asUint8List(), //element.barcode ?? '',
        ]);
      }

      for (var element in excelExport) {
        sheetObject.appendRow(element);
      }
      List<int>? data4 = excel.encode();
      if (data4 == null) {
        failedAlert(error: Trans.operationFalied.trans());
        return;
      }

      Directory? downloadsDirectory;
      if (kIsWeb != true) {
        if (Platform.isAndroid) {
          // downloadsDirectory = await DownloadsPath.downloadsDirectory();
          downloadsDirectory = await getApplicationDocumentsDirectory();
        } else {
          downloadsDirectory = await getApplicationDocumentsDirectory();
        }
        if (downloadsDirectory == null) {
          failedAlert(error: Trans.operationFalied.trans());
          return;
        }
        final String path = downloadsDirectory.path;
        final dir = await Directory(path).create(recursive: true);
        final fullPath =
            "${dir.path}/${Trans.priceList.trans()} ${DateTime.now().toString().split(".")[0].replaceAll(":", "-")}.xlsx";
        File file = File((fullPath));

        if (await file.exists()) {
          await file.delete();
        }
        file
          ..createSync(recursive: true)
          ..writeAsBytesSync(data4);

        Helper.i.pop();
        Helper.i.pop();
        if (!share) {
          openFileAlert(path: fullPath);
        } else {
          Share.shareXFiles([XFile(fullPath)]);
        }
      } else {
        MimeType type = MimeType.microsoftExcel;
        await FileSaver.instance.saveFile(
            name:
                "${Trans.accountStatments.trans()} ${DateTime.now().toString().split(".")[0].replaceAll(":", "-")}",
            bytes: Uint8List.fromList(data4),
            ext: "xlsx",
            mimeType: type);
        Helper.i.pop();
        Helper.i.pop();
      }
    } catch (e, c) {
      recoredError(e, c);
      logger(e);
      Helper.i.pop();
      Helper.i.pop();
      Helper.i.pop();
      failedAlert(error: Trans.operationFalied.trans());
    }
  }

Solution

  • I've recently added the functionality to the Excel package. While it's still under review as an open Pull Request, you can already use it in your project by specifying the following dependency in your pubspec.yaml:

    dependencies:
      excel:
        git:
          url: https://github.com/andrzejchm/excel.git
          ref: main
    

    After adding the dependency, you can use the following code to add images to cells:

    import 'package:excel/excel.dart';
    
    void main() async {
      // Create a new Excel file
      final excel = Excel.createExcel();
    
      // Get or create a sheet to add your images
      final imageSheet = excel['Images'];
    
      // Find the cell where you want to insert the image
      final imageCell = imageSheet.cell(CellIndex.indexByString('A1'));
    
      // Assign an ImageCellValue to the cell
      imageCell.value = await ImageCellValue.fromFile(
        'path/to/your/image.png', // Path to your image file
        width: 100,              // Width of the image (in points, converted to EMUs internally)
        height: 100,             // Height of the image (in points, converted to EMUs internally)
      );
    
      // Convert the excel object to raw file bytes that can be then saved to a file.
      final fileBytes = excel.save();
      
    }
    

    Just replace 'path/to/your/image.png' with the actual path to your image file.