15

I have List<> data

List<dynamic> associateList = [
{"number": 1, "lat": "14.97534313396318", "lon": "101.22998536005622"},
{"number": 2, "lat": "14.97534313396318", "lon": "101.22998536005622"},
{"number": 3, "lat": "14.97534313396318", "lon": "101.22998536005622"},
{"number": 4, "lat": "14.97534313396318", "lon": "101.22998536005622"}];

and I want csv file like it.

enter image description here

and How to export files to the device?

2

4 Answers 4

20

You can copy paste run full code below
The following working demo write file to Downloads directory and view file with CSV Viwer
Step 1: Add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to AndroidManifest.xml
Step 2: request permission with package permission_handler
Step 3: get Downloads directory with package ext_storage
Step 4: use package csv's ListToCsvConverter()

code snippet

Map<Permission, PermissionStatus> statuses = await [
  Permission.storage,
].request();

List<dynamic> associateList = [
  {"number": 1, "lat": "14.97534313396318", "lon": "101.22998536005622"},
  {"number": 2, "lat": "14.97534313396318", "lon": "101.22998536005622"},
  {"number": 3, "lat": "14.97534313396318", "lon": "101.22998536005622"},
  {"number": 4, "lat": "14.97534313396318", "lon": "101.22998536005622"}
];

List<List<dynamic>> rows = [];

List<dynamic> row = [];
row.add("number");
row.add("latitude");
row.add("longitude");
rows.add(row);
for (int i = 0; i < associateList.length; i++) {
  List<dynamic> row = [];
  row.add(associateList[i]["number"] - 1);
  row.add(associateList[i]["lat"]);
  row.add(associateList[i]["lon"]);
  rows.add(row);
}

String csv = const ListToCsvConverter().convert(rows);

String dir = await ExtStorage.getExternalStoragePublicDirectory(
    ExtStorage.DIRECTORY_DOWNLOADS);
print("dir $dir");
String file = "$dir";

File f = File(file + "/filename.csv");

f.writeAsString(csv);

working demo

enter image description here

full code

import 'package:csv/csv.dart';
import 'package:flutter/material.dart';
import 'package:ext_storage/ext_storage.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';

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

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

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _generateCsvFile() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    List<dynamic> associateList = [
      {"number": 1, "lat": "14.97534313396318", "lon": "101.22998536005622"},
      {"number": 2, "lat": "14.97534313396318", "lon": "101.22998536005622"},
      {"number": 3, "lat": "14.97534313396318", "lon": "101.22998536005622"},
      {"number": 4, "lat": "14.97534313396318", "lon": "101.22998536005622"}
    ];

    List<List<dynamic>> rows = [];

    List<dynamic> row = [];
    row.add("number");
    row.add("latitude");
    row.add("longitude");
    rows.add(row);
    for (int i = 0; i < associateList.length; i++) {
      List<dynamic> row = [];
      row.add(associateList[i]["number"] - 1);
      row.add(associateList[i]["lat"]);
      row.add(associateList[i]["lon"]);
      rows.add(row);
    }

    String csv = const ListToCsvConverter().convert(rows);

    String dir = await ExtStorage.getExternalStoragePublicDirectory(
        ExtStorage.DIRECTORY_DOWNLOADS);
    print("dir $dir");
    String file = "$dir";

    File f = File(file + "/filename.csv");

    f.writeAsString(csv);

    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _generateCsvFile,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think you use the default flutter increment code :), I wish you could update your answer :)
In working demo, each data inside a row listing in different column. But when I trying same code, each row is placing in same column not separated. How can we show it on different column ?
Most of the code can be minimized using this package of you.pub.dev/packages/to_csv.
The ext_storage package seems to be deprecated. But path_provider seems to do the trick with: _externalDocumentsDirectory = getExternalStorageDirectory(); at least in android.
2

To export the list to a CSV file in Flutter, you can use the csv package like this:

import 'dart:io';
import 'package:csv/csv.dart';

void main() {
  List<Map<String, dynamic>> associateList = [
    {"number": 1, "lat": "14.97534313396318", "lon": "101.22998536005622"},
    {"number": 2, "lat": "14.97534313396318", "lon": "101.22998536005622"},
    {"number": 3, "lat": "14.97534313396318", "lon": "101.22998536005622"},
    {"number": 4, "lat": "14.97534313396318", "lon": "101.22998536005622"}
  ];

  exportCSV(associateList);
}

void exportCSV(List<Map<String, dynamic>> list) {
  List<List<dynamic>> rows = [];
  rows.add(["number", "lat", "lon"]);

  for (var map in list) {
    rows.add([map["number"], map["lat"], map["lon"]]);
  }

  String csv = const ListToCsvConverter().convert(rows);
  String dir = (await getExternalStorageDirectory()).path;
  String filePath = "$dir/list.csv";

  File file = File(filePath);
  await file.writeAsString(csv);

  print("File exported successfully!");
}

Comments

0

I have create a CSV file Using A to D width and Hight is 1 to 50

add tree library in Yaml file

 syncfusion_flutter_xlsio: ^20.1.60-beta
  path_provider: ^2.0.11
  open_file: ^3.2.1

if Column, Row in override issue

import 'package:syncfusion_flutter_xlsio/xlsio.dart' hide Column,  Row;

you can check only creatExcel()

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      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
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            creatExcel();
          },
          child: Text("creat Excel"),
        ),
      ),
    );
  }

  creatExcel() async {
    Workbook workbook = Workbook();
// Accessing worksheet via index.
    final Worksheet sheet = workbook.worksheets[0];

    for (var i = 1; i < 50; i++) {
      sheet.getRangeByName('A$i').setText('Hello World!');
      sheet.getRangeByName('B$i').setText('Hello World!');
      sheet.getRangeByName('C$i').setText('Hello World!');
      sheet.getRangeByName('D$i').setText('Hello World!');
    }

    final List<int> bytes = workbook.saveAsStream();
    workbook.dispose();
    final String path = (await getApplicationDocumentsDirectory()).path;
    final String filename = '$path/output.xlsx';
    final File file = File(filename);

    await file.writeAsBytes(bytes, flush: true);
    OpenFile.open(filename);
  }
}

Comments

0

This package is well described and very easy to use for generating csv/excel files... pub.dev/packages/to_csv. This also minimize most of the code given in the answer by @chunhunghan

Code

import 'package:to_csv/to_csv.dart' as exportCSV;


List<String> header = [];
header.add('No.');
header.add('User Name');
header.add('Mobile');
header.add('ID Number');

List<List<String>> listOfLists = [];
List<String> data1 = ['1','Bilal Saeed','1374934','912839812']; 
List<String> data2 = ['2','Ahmar','21341234','192834821'];

listOfLists.add(data1);
listOfLists.add(data2);

exportCSV.myCSV(header, listOfLists);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.