We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Export local Json data into a excel file using syncfusion_flutter_xlsio

Hello togther,

i am trying to transfer data from a local Json file into a excel file.

I am using the path_provider package to access the local Json file and syncfusion_flutter_xlsio to create a write to the excel file

The structure of the Json is as follows

```

{
"measure": [
{
"count": 2,
"range_array": [
16,
25
],
"force_array": [
35,
72
]
},
{
"count": 4,
"range_array": [
18,
31
],
"force_array": [
26,
55
]
}
]
}

```

In the following code I am able already to get the data inside the Json into the excel but only declaring it one by one.

```

worksheet.getRangeByName('A1').setText('Count');
worksheet.getRangeByName('A2').setValue(jsonData["measure"]![0]["count"]);
worksheet.getRangeByName('B1').setText('Range Array');
worksheet.getRangeByName('B2').setValue(jsonData["measure"]![0]["range_array"]);
worksheet.getRangeByName('c1').setText('Force Array');
worksheet.getRangeByName('C2').setValue(jsonData["measure"]![0]["force_array"]);
worksheet.getRangeByName('A3').setValue(jsonData["measure"]![1]["count"]);
worksheet.getRangeByName('B3').setValue(jsonData["measure"]![1]["range_array"]);
worksheet.getRangeByName('C3').setValue(jsonData["measure"]![1]["force_array"]);

```

But i would need instead to be able to declare it by indexing true the Json file and write it to the Excel.

In the following example i am able to index true the Json and show it in a Listview.

```

ListView.builder(
itemCount: data!['measure'].length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Count: ${data!['measure'][index]['count']}',
style: const TextStyle(fontSize: 18.0),
),
const SizedBox(height: 8.0),
Text(
'Range Array: ${data!['measure'][index]['range_array']}',
style: const TextStyle(fontSize: 18.0),
),
const SizedBox(height: 8.0),
Text(
'Force Array: ${data!['measure'][index]['force_array']}',
style: const TextStyle(fontSize: 18.0),
),
],
),
),
);
},
),

```

Is it possible to make it also when i am trying to create and write to the excel file?

Follows the complete code from what i have until now.

Thanks in advance for some help.

```

// ignore_for_file: avoid_print

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart' hide Column;
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'dart:convert';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);

final String title;

@override
MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
Map<String, dynamic>? data;

@override
void initState() {
super.initState();
_getData();
}

_getData() async {
try {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/data.json');
String jsonString = await file.readAsString();
data = jsonDecode(jsonString);
setState(() {});
} catch (e) {
print(e);
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Json to Excel"),
actions: <Widget>[
IconButton(
constraints: const BoxConstraints.expand(width: 80),
icon: const Text('CREATE Excel', textAlign: TextAlign.center),
onPressed: () {
importJsonData();
},
),
],
),
body: data == null
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: data!['measure'].length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Count: ${data!['measure'][index]['count']}',
style: const TextStyle(fontSize: 18.0),
),
const SizedBox(height: 8.0),
Text(
'Range Array: ${data!['measure'][index]['range_array']}',
style: const TextStyle(fontSize: 18.0),
),
const SizedBox(height: 8.0),
Text(
'Force Array: ${data!['measure'][index]['force_array']}',
style: const TextStyle(fontSize: 18.0),
),
],
),
),
);
},
),
);
}

void importJsonData() async {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/data.json');
String jsonString = await file.readAsString();
final jsonData = jsonDecode(jsonString);
setState(() {});

// Create a new Workbook
final Workbook workbook = Workbook();
final Worksheet worksheet = workbook.worksheets[0];

// Add data to cells

worksheet.getRangeByName('A1').setText('Count');
worksheet.getRangeByName('A2').setValue(jsonData["measure"]![0]["count"]);
worksheet.getRangeByName('B1').setText('Range Array');
worksheet.getRangeByName('B2').setValue(jsonData["measure"]![0]["range_array"]);
worksheet.getRangeByName('c1').setText('Force Array');
worksheet.getRangeByName('C2').setValue(jsonData["measure"]![0]["force_array"]);
worksheet.getRangeByName('A3').setValue(jsonData["measure"]![1]["count"]);
worksheet.getRangeByName('B3').setValue(jsonData["measure"]![1]["range_array"]);
worksheet.getRangeByName('C3').setValue(jsonData["measure"]![1]["force_array"]);

// Save the workbook to a file
// Save and dispose workbook.
final List<int> bytes = workbook.saveAsStream();
await saveAndLaunchFile(bytes, 'Measure.xlsx');
}
}

Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
String? path;

final Directory directory = await getApplicationSupportDirectory();
path = directory.path;

final File file = File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName');
await file.writeAsBytes(bytes, flush: true);

await Process.run('start', <String>['$path\\$fileName'], runInShell: true);
}


```


The Excel file would need to look like this


excel2.png



3 Replies

KK Konduru Keerthi Konduru Ravichandra Raju Syncfusion Team December 28, 2022 12:52 PM UTC

Hi Carlos,

 

We are sorry to inform you that it is not possible to iterate through data automatically in Syncfusion Flutter XlsIO, as requested.


Regards,

Keerthi.



CC Carlos Costa replied to Konduru Keerthi Konduru Ravichandra Raju December 28, 2022 03:12 PM UTC

Hi Keerthi,

thanks for the reply.

I could manage it as follows.

What i do not like in my approach is to use a lot of time join("") function to remove the brackets.

```

_getData() async {
try {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/data.json');
String jsonString = await file.readAsString();
data = jsonDecode(jsonString);
setState(() {});
} catch (e) {
print(e);
}
}

void importJsonData() async {
// Create a new Workbook
final Workbook workbook = Workbook();
final Worksheet worksheet = workbook.worksheets[0];

//Initialize the list
List measure = data!['measure'];

List<Object> listCount = [], listRange = [], listForce = [];

worksheet.getRangeByName('A1').setText('Count');
worksheet.getRangeByName('B1').setText('Range');
worksheet.getRangeByName('C1').setText('Force');

for (var i = 0; i < measure.length; i++) {
listCount.add({
{measure[i]['count']}.join('')
}.join(''));
listRange.add({
{measure[i]['range_array'].join(',')}.join('')
}.join(''));
listForce.add({
{measure[i]['force_array'].join(',')}.join('')
}.join(''));

worksheet.importList(listCount, 2, 1, true);
worksheet.importList(listRange, 2, 2, true);
worksheet.importList(listForce, 2, 3, true);
}

// Save the workbook to a file
final List<int> bytes = workbook.saveAsStream();
await saveAndLaunchFile(bytes, 'Measure.xlsx');
}


```



KK Konduru Keerthi Konduru Ravichandra Raju Syncfusion Team December 29, 2022 11:26 AM UTC

Carlos, on analysis, we found that using the join function is required to achieve your requirement. Please get back to us if you have any other queries.


Loader.
Up arrow icon