Json to Excel in Flutter | Export Json data to Excel Sheet in Flutter Android and iOS | Json to Excel

parsing json data in flutter

Json to Excel

Add Dependencies

To export Json to Excel and download in Flutter first add packages in pubspec.yaml

dependencies: 
    excel:    # to convert json data into excel
    path_provider: # for directory path/download file path

Example

import 'dart:convert';
import 'dart:io';
import 'package:excel/excel.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('JSON to Excel Example'),
        ),
        body: JsonToExcelExample(),
      ),
    );
  }
}

class JsonToExcelExample extends StatelessWidget {
  Future<void> _convertJsonToExcel(BuildContext context) async {
    // Sample JSON data
    List<Map<String, dynamic>> jsonData = [
      {'Name': 'John Doe', 'Age': 25, 'City': 'New York'},
      {'Name': 'Jane Doe', 'Age': 30, 'City': 'San Francisco'},
      // Add more data as needed
    ];

    // Create an Excel workbook
    var excel = Excel.createExcel();
    var sheet = excel['Sheet1'];

    // Add headers
    sheet.appendRow(['Name', 'Age', 'City']);

    // Add data from JSON
    for (var item in jsonData) {
      sheet.appendRow([item['Name'], item['Age'], item['City']]);
    }

    // Save the Excel file 
    //For iOS The info.plist file is found in the IOS module of your flutter project(ios/Runner/info.plst) and Android update AndroidManifest.xml file
    var excelFile = await excel.encode();
    var directory = await getExternalStorageDirectory(); // Get the external storage directory. 
    var filePath = '${directory.path}/example.xlsx';

    File file = File(filePath);
    await file.writeAsBytes(excelFile);

    print('Excel file saved as: $filePath');

    // Show a SnackBar with the download option
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Excel file saved successfully.'),
        action: SnackBarAction(
          label: 'Download',
          onPressed: () {
            // Open the file using a file explorer
            Process.run('open', [filePath]);
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () {
          _convertJsonToExcel(context);
        },
        child: Text('Convert JSON to Excel and Download'),
      ),
    );
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.