Articles in this section
Category / Section

How to add images to Excel worksheet programmatically in Flutter ?

2 mins read

Syncfusion Flutter XlsIO library is used to create and modify Excel documents. Using this library, you can add images like JPEG and PNG formats to an Excel worksheet using Flutter.

Steps to add Images to the Excel document programmatically.


Step 1: Create a new Flutter application project.

  1. Open Visual Studio Code (After installing the Dart and Flutter extensions as stated in this setup editor page)
  2. Click View -> Command Palette…

Command Palette...

  1. Type Flutter and choose Flutter: New Project.

Flutter - New Project

  1. Enter the project name and press the Enter button.
  2. Now choose the location of the project.

 

Step 2: Add the following code in your pubspec.yaml file to install the syncfusion flutter xlsio package in your application. It will be automatically downloaded from the pub once you trigger the flutter pub get comment or Get packages option from the Visual Studio Code.

dependencies:
   syncfusion_flutter_xlsio: ^18.4.31-beta

 

Import the following package in your main.dart file.

import 'package:syncfusion_flutter_xlsio/xlsio.dart' ;

 

Step 3: Add the following code in the lib/main.dart file to create a simple button.

 

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              child: const Text(
                'Generate Excel',
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.blue,
              onPressed: _addImageToExcel,
            )
          ],
        ),
      ),
    );
  }

 

Step 4: Use the following code to load an image in the Flutter project.

  1. Add the following code in your pubspec.yaml file.
    flutter:
      # To add assets to your application, add an assets section, like this:
      assets:
        - images/
    

 

  1. Import the following package in your main.dart file.
    import 'dart:convert';
    import 'package:flutter/services.dart';
    

 

  1. Add the following code in lib/main.dart file to read an image.
    Future<List<int>> _readImageData(String name) async {
        final ByteData data = await rootBundle.load('images/$name');
        return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      }
     
    

 

Step 5: Add the following code to the _addImageToExcel()  function to add Images to a Excel document programmatically.

Future<void> _addImageToExcel() async {
    //Create a Excel document.
    //Creating a workbook.
    final Workbook workbook = Workbook();
 
    //Accessing via index
    final Worksheet sheet = workbook.worksheets[0];
 
    final String image = base64.encode(await _readImageData('image.jpg'));
 
    // Add image to Excel worksheet.
    sheet.pictures.addBase64(1, 1, image);
 
    //Save and launch the excel.
    final List<int> bytes = workbook.saveAsStream();
 
    //Dispose the document.
    workbook.dispose();
  }

 

Step 6: Use the following code to save and launch the generated Excel file.

  1. Add the following dependencies in your pubspec.yaml file.
    path_provider: ^1.6.7
    open_file: ^3.0.1   #Open source library to launch the Excel file in mobile devices
    

 

  1. Import the following packages in your main.dart file.
    import 'dart:io'; 
    import 'package:path_provider/path_provider.dart';
    import 'package:open_file/open_file.dart';
    

 

  1. Include the following code snippet in the _addImageToExcel() method to open the Excel document in the mobile‘s default application (any Excel application).
     //Get the storage folder location using path_provider package.
     final Directory directory = await getExternalStorageDirectory();
     //Get directory path
     final String path = directory.path;
     //Create an empty file to write Excel data
     final File file = File('$path/ExcelImage.xlsx');
     //Write Excel data
     await file.writeAsBytes(bytes, flush: true);
     //Launch the file (used open_file package)
     await OpenFile.open('$path/ExcelImage.xlsx');
    

 

Step 7: Run the sample using the flutter run command. This will add Image to the Excel document.

After the application launches, you will get the Excel document below.

 

A picture containing calendar

Description automatically generated

Output Excel document created using XlsIO

You can download the complete work sample from add-image-to-excel.zip.

Take a moment to peruse the documentation for working with image, where you can find other options like inserting, re-sizing, flipping and rotating images in Excel. Also, find the features like charts, protect Excel documents, and more with code examples.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied