【问题标题】:Saving an excel file to a device using Flutter使用 Flutter 将 excel 文件保存到设备
【发布时间】:2021-06-13 15:22:31
【问题描述】:

我想保存一个我在 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);
    });

有人知道最好的方法吗?

【问题讨论】:

  • 我最终从 excel 切换并使用了 syncfusion_flutter_xlsio 以及 path_provider 和 open_file 包。但我认为 excel 包也可以与 open_file 一起使用,因为它允许我打开我已经修改过的文件,然后保存并从那里导出。包裹:pub.dev/packages/open_file

标签: ios excel flutter dart


【解决方案1】:

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

您需要按照以下步骤操作:

  1. 找到正确的本地路径。
    • pubspec.yaml 中包含path_provider
    • 计算目标父目录的路径,例如文档目录:
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());
}

【讨论】:

  • 如果我使用 getApplicationDocumentsDirectory() 创建这些文件,您知道我可以在哪里访问这些文件,那就是设备上的哪个位置?我的意思是 getApplicationDocumentsDirectory() 真正导致了哪里?
  • 在不阅读文档/使用搜索的情况下检查它的最简单方法是打印file.path。此外,path_provider API 提到了两个地方:iOS 上的 NSDocumentDirectory 和 Android 上的 dataDirectory (getDataDirectory):pub.dev/documentation/path_provider/latest/path_provider/…
  • 我最终使用了这个路径,但是那里没有保存 excel 文件(使用@mightybruno 回答)。我也在寻找一种更加用户友好的方式来将 Excel 文件保存在用户的设备上。我不想从 Xcode 下载容器来查看文件,如果它们甚至会出现在那里......也许还有其他一些我需要使用的颤振包。
  • 这些文件有多大?
  • 一点也不大。每个仅包含文本的 Excel 文件使用 4 列和 1-12 行。他们应该出现在我的移动设备上的什么地方?只能通过 Xcode 下载吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
  • 2021-10-12
  • 1970-01-01
相关资源
最近更新 更多