如何在flutter中创建和导出csv文件?

0yycz8jy  于 2023-04-07  发布在  Flutter
关注(0)|答案(4)|浏览(336)

我有列表〈〉数据

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"}];

我想要一个像这样的csv文件。

以及如何将文件导出到设备?

nuypyhwy

nuypyhwy1#

你可以复制粘贴下面运行完整的代码
下面的工作演示将文件写入Downloads目录并使用CSV Viwer查看文件
步骤1:将<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />添加到AndroidManifest.xml
步骤2:使用包permission_handler请求权限
步骤3:获取包含ext_storage包的Downloads目录
步骤4:使用csv包的ListToCsvConverter()
代码片段

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);

工作演示

全码

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),
      ),
    );
  }
}
8ehkhllq

8ehkhllq2#

我已经创建了一个CSV文件使用A到D的宽度和高度是1至50
在Yaml文件中添加树库

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

如果列、行在覆盖问题中

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

只能选中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);
  }
}
z2acfund

z2acfund3#

这个包描述得很好,非常容易使用生成csv/excel文件...pub.dev/packages/to_csv。这也最大限度地减少了@chunhunghan的答案中给出的大部分代码

编码

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);
sigwle7e

sigwle7e4#

要在Flutter中将列表导出到CSV文件,您可以像这样使用csv包:

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!");
}

相关问题