Articles in this section
Category / Section

How to create Excel charts in an Excel programmatically in Flutter?

2 mins read

Syncfusion Flutter XlsIO library is used to create and modify Excel documents. Using this library, you can also create and modify Excel charts in an Excel document. Excel charts in the Excel worksheets help visualize data in a graphical structure.

Steps to create Excel charts in an 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 OfficeChart 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.

If you add OfficeChart package in your dependency, it will automatically fetch the Syncfusion XlsIO package while getting the OfficeChart package on your machine.

 

dependencies: 
   syncfusion_officechart: ^18.4.31-beta

 

Import the following package in your main.dart file.

import 'package:syncfusion_flutter_xlsio/xlsio.dart' ;
import 'package:syncfusion_officechart/officechart' ;

 

Step 3: Add the following code in 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 Chart',
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.blue,
              onPressed: _generateExcelChart,
            )
          ],
        ),
      ),
    );
  }

 

Step 4: Add the following code to the _generateExcelChart() function to create an Excel chart in a document programmatically.

Future<void> _generateExcelChart() async {
    // Create the  Excel document.
    // Creating a workbook.
    final Workbook workbook = Workbook();
 
    // Accessing via index
    final Worksheet sheet = workbook.worksheets[0];
 
    // Setting value in the cell.
    sheet.getRangeByName('A1').setText('Months');
    sheet.getRangeByName('B1').setText('Internal Sales Amount');
    sheet.getRangeByName('C1').setText('Reseller Sales Amount');
    sheet.getRangeByName('A2').setDateTime(DateTime(2014, 01, 14, 14, 14, 14));
    sheet.getRangeByName('A3').setDateTime(DateTime(2014, 02, 14, 14, 14, 14));
    sheet.getRangeByName('A4').setDateTime(DateTime(2014, 03, 14, 14, 14, 14));
    sheet.getRangeByName('A5').setDateTime(DateTime(2014, 04, 14, 14, 14, 14));
    sheet.getRangeByName('A6').setDateTime(DateTime(2014, 05, 14, 14, 14, 14));
    sheet.getRangeByName('B2').setNumber(700);
    sheet.getRangeByName('B3').setNumber(200);
    sheet.getRangeByName('B4').setNumber(300);
    sheet.getRangeByName('B5').setNumber(500);
    sheet.getRangeByName('B6').setNumber(800);
    sheet.getRangeByName('C2').setNumber(30);
    sheet.getRangeByName('C3').setNumber(40);
    sheet.getRangeByName('C4').setNumber(70);
    sheet.getRangeByName('C5').setNumber(2);
    sheet.getRangeByName('C6').setNumber(100);
 
    // Create an instance of chart collection.
    final ChartCollection charts = ChartCollection(sheet);
 
    // Add the chart.
    final Chart chart = charts.add();
 
    // Set Chart Type.
    chart.chartType = ExcelChartType.line;
 
    // Set data range in the worksheet.
    chart.dataRange = sheet.getRangeByName('A1:C6');
    chart.isSeriesInRows = false;
 
    // Setting chart title with font properties
    chart.chartTitle = 'Yearly Sales';
    chart.chartTitleArea.bold = true;
    chart.chartTitleArea.size = 12;
 
    // Setting legend position.
    chart.legend.position = ExcelLegendPosition.bottom;
 
    // Setting the chart position.
    chart.topRow = 0;
    chart.bottomRow = 20;
    chart.leftColumn = 1;
    chart.rightColumn = 8;
 
    // Setting Axis number format.
    chart.primaryCategoryAxis.numberFormat = 'mmmm';
    chart.primaryValueAxis.numberFormat = '0.00';
 
      // Setting line pattern.
  chart.plotArea.linePattern = ExcelChartLinePattern.solid;
  chart.plotArea.linePatternColor = '#00FFFF';
  chart.linePattern = ExcelChartLinePattern.longDashDotDot;
  chart.linePatternColor = '#0000FF';

  // Set charts to worksheet.
  sheet.charts = charts;

  // Save and launch the Excel.
  final List<int> bytes = workbook.saveAsStream();
  // Dispose the document.
  workbook.dispose();
}

 

Step 5: 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 _generateExcelChart() 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/ExcelChart.xlsx');
    // Write Excel data
    await file.writeAsBytes(bytes, flush: true);
    // Launch the file (used open_file package)
    await OpenFile.open('$path/ExcelChart.xlsx');

 

Step 6: Run the sample using the flutter run command. This creates Excel charts in an Excel document.

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

Chart, line chart

Description automatically generated

Output Excel document created using XlsIO

You can download the complete work sample from create-excel-chart.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 create Excel charts programmatically in Flutter.

 

You can refer to our XlsIO’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 (0)
Please  to leave a comment
Access denied
Access denied