我正在使用google drive API在Flutter应用程序中下载excel文件,但我想将下载的文件内容响应存储在文件中,然后使用excel dart包进行一些更新操作,下面是从路径位置读取xlsx文件的给定代码。
var file = "Path_to_pre_existing_Excel_File/excel_file.xlsx"; //here I want to store the response from drive api
var bytes = File(file).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
//Do some logic here
for (var table in excel.tables.keys) {
print(table); //sheet Name
print(excel.tables[table].maxCols);
print(excel.tables[table].maxRows);
for (var row in excel.tables[table].rows) {
print("$row");
}
}
//then saving the excel file
// updating the excel sheet to Drive
updateToDrive(excel,fileId);
我已经创建了所有必需的身份验证功能、驱动范围,我的下载功能如下所示:
Future<void> downloadFile() async{
String fileId = '1TOa4VKfZBHZe######WLA4M95nOWp';
final response = await driveApi.files.get(
fileId,
downloadOptions: drive.DownloadOptions.fullMedia
);
print(response);
}
此函数执行正确,并提供媒体类型的响应,但我无法读取此响应以便将其存储在文件中。任何帮助都将不胜感激,谢谢
我把下载函数改成了这个,因为drive.files.get((返回了一个Future对象,所以我把它改成了返回Future<媒体>通过类型铸造。
String fileId = "19jF3lOVW563LU6m########jXVLNQ7poXY1Z";
drive.Media? response = (await driveApi.files.get(
fileId,
downloadOptions: drive.DownloadOptions.fullMedia
)) as drive.Media?;
现在响应是一个媒体,我们可以在上面收听sream,将响应存储在文件中。要做到这一点,我们首先需要通过path_provider 获取应用程序目录
final String path = (await getApplicationSupportDirectory()).path;
final String fileName = '$path/Output.xlsx';
File file = File(fileName);
现在我们要编写响应流stream<列表>进入我们的文件对象,我从这个链接中找到
List<int> dataStore = [];
await response!.stream.listen((data) {
print("DataReceived: ${data.length}");
dataStore.insertAll(dataStore.length, data);
}, onDone: () {
print("Task Done");
file.writeAsBytes(dataStore);
OpenFile.open(file.path);
print("File saved at ${file.path}");
}, onError: (error) {
print("Some Error");
});
现在我们可以通过excel包做任何我们想做的改变。