Articles in this section
Category / Section

How to add images to Excel worksheet programmatically in Flutter web platform?

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 Excel worksheet programmatically in Flutter Web platform.


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 Application 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 command or Get packages option from 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: _addFormulasToExcel,
          )
        ],
      ),
    ),
  );
}

 

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/image.jpg

 

  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 worksheet 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.
    final Picture picture = sheet.pictures.addBase64(1, 1, image);
 
    // Resize an image
    picture.height = 200;
    picture.width = 200;
 
    // Save and launch the excel.
    final List<int> bytes = workbook.saveAsStream();
 
    // Dispose the document.
    workbook.dispose();
 }

 

Step 6: Use the following code to download the generated Excel file in the web platform.

  1. Import the following packages in your main.dart file.
    import 'dart:convert';
    import 'dart:html';
    

 

  1. Include Include the following code snippet in the _addImageToExcel() method to download the Excel document in the web application (any browser).
    // Download the output file.
    AnchorElement(
      href:
          "data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}")
      ..setAttribute("download", "ExcelImage.xlsx")
      ..click();

 

Step 7: To run the sample in the web platform, follow the steps given in Building a web application with Flutter. Using the flutter run -d chrome command, launch the application in the Chrome browser. This creates an Excel document with an image.

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

Output image 1

Screenshot of the application.

Output 2

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, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through formulas, adding charts in worksheets or workbooks, organizing and analyzing data through tables and pivot tables, appending multiple records to a worksheet using template markers, and most importantly, PDF and image conversions, etc., with code examples.

Refer here to explore the rich set of Syncfusion Essential XlsIO features.

 

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from the trial setup or from the NuGet feed, include a license key in your projects. Refer to this link to learn about generating and registering a Syncfusion license key in your application to use the components without a trial message.

 

Conclusion

I hope you enjoyed learning about how to add images to Excel worksheet programmatically in Flutter web platform in XlsIO.

 

You can refer to our XIsIO’s feature tour page to learn about its other groundbreaking features. Explore our UG documentation and online demos to understand how to manipulate data in Excel documents. 

If you are an existing user, you can access our latest components from the License and Downloads page. For new users, you can try our 30-day free trial to check out XlsIO and other Syncfusion components.

If you have any queries or require clarification, please let us know in the comments below or contact us through our support forums or feedback portal. We are always happy to assist you!

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