使用Flutter将excel文件保存到设备



我想在flutter应用程序中保存一个动态生成的excel文件。我想将文件保存在用户设备上,该设备将在移动设备上。然而,我正试图弄清楚在哪里以及如何保存它

这就是我迄今为止使用flutter:的excel包所做的

https://pub.dev/packages/excel

// Some function code...
// Trying to save the file somewhere on a device
excel.encode().then((onValue) {
File("/some/filepath/but/not/sure/where/it/should/go")
..createSync(recursive: true)
..writeAsBytesSync(onValue);
});

有人知道最好的方法吗?

根据Read and write files食谱:https://flutter.dev/docs/cookbook/persistence/reading-writing-files

您需要遵循以下步骤:

  1. 找到正确的本地路径。
    • pubspec.yaml中包含path_provider
    • 计算目标父目录的路径,例如documents-dir:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
  1. 创建对文件位置的引用
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/filename.xlsx');
}
  1. 将数据写入文件
Future<File> writeCounter(Excel excel) async {
final file = await _localFile;
return file.writeAsBytes(excel.encode());
}

最新更新