我正在创建一个应用程序,我将发送一封附带excel表格的电子邮件。 我已经有了excel表,我的应用程序将在发送之前将一些数据添加到excel表。
但是,在尝试将excel工作表添加到我的资源文件夹后,将路径添加到pubspec.yaml,File类找不到该文件。
pubspec.yaml:
assets:
- logo.png
- Declaratieformulier.xlsx
功能:
openFile() {
var bytes = new File("assets/Declaratieformulier.xlsx").readAsBytesSync();
var decoder = new SpreadsheetDecoder.decodeBytes(bytes);
var table = decoder.tables['Blad1'];
我做了一点挖掘,发现资产没有作为文件放在设备上,但包含在APK中。
所以我的问题是:如何在我的应用程序中包含Excel工作表,以便我可以阅读并将其另存为手机上的新Excel文件?
您需要使用Flutter rootBundle读取文件。正如@LorenzOliveto所说,您还需要修复pubspec.yaml声明。
ByteData data = await rootBundle.load("assets/Declaratieformulier.xlsx");
// This would be your equivalent bytes variable
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// You can also copy it to the device when the app starts
final directory = await getApplicationDocumentsDirectory();
String filePath = join(directory, "Declaratieformulier.xlsx");
await File(filePath).writeAsBytes(bytes);
您必须在pubspec.yaml
中插入完整路径,因此您必须添加Declaratieformulier.xlsx
而不是assets/Declaratieformulier.xlsx
。
assets:
- logo.png
- assets/Declaratieformulier.xlsx
您还应该读取根包的文件
import 'package:flutter/services.dart' show ByteData, rootBundle;
...
ByteData data = await rootBundle.load("assets/Declaratieformulier.xlsx");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
var decoder = SpreadsheetDecoder.decodeBytes(bytes);