推荐库
- spreadsheet_decoder
- excel
方案一:spreadsheet_decoder
加入依赖
dependencies: flutter: sdk: flutter spreadsheet_decoder: ^2.1.1 //https://pub.flutter-io.cn/packages/spreadsheet_decoder
必要的初始化
import 'dart:io';import 'package:spreadsheet_decoder/spreadsheet_decoder.dart';var bytes = File.fromUri("填你文件的地址.xlsx").readAsBytesSync(); var decoder = SpreadsheetDecoder.decodeBytes(bytes);
查看有多少个工作表
print((decoder.tables).keys);
使用某个表
var table = decoder.tables['Sheet1'];
获取数据
print(table!.rows[0][3]);#获取第一行第三列print(table!.rows[0]);#获取第一行所有
修改数据
decoder.updateCell('Sheet1', 0, 0, 1337);//修改第一行第一列的数据为1337
保存数据(官方文档中这里他少了个括号会报错,以下修改为正确的了)
File(join("你的地址.xlsx")).writeAsBytesSync(decoder.encode());
方案二:excel
加入依赖
dependencies: excel: 2.0.1 #https://pub.flutter-io.cn/packages/excel
读取
var file = "Path_to_pre_existing_Excel_File/excel_file.xlsx"; var bytes = File(file).readAsBytesSync(); var excel = Excel.decodeBytes(bytes); 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"); } }
从Asset资源中读取
import 'package:flutter/services.dart' show ByteData, rootBundle; ByteData data = await rootBundle.load("assets/existing_excel_file.xlsx"); var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); var excel = Excel.decodeBytes(bytes); 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"); } }
创建excel文件
var excel = Excel.createExcel(); // automatically creates 1 empty sheet: Sheet1
更新修改数据(这里就不复制官方的了,自己总结的)
var bytes = File("你的文件.xlsx").readAsBytesSync();var excel = Excel.decodeBytes(bytes); Sheet sheetObject = excel['Sheet1']; //两种方法 //1、updateCell 同样这里的1,1是B2;0,0就是A1 sheetObject.updateCell( CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 1), "测试测试"); //2、cell这个直观些,将W29.value的值改为xxx sheetObject.cell(CellIndex.indexByString('W29')).value = "测测测试";
保存
在flutter web中
// when you are in flutter web then save() downloads the excel file. // Call function save() to download the file var fileBytes = excel.save(fileName: "My_Excel_File_Name.xlsx");
在安卓/ios
需要下载添加path_provider库
var fileBytes = excel.save(); var directory = await getApplicationDocumentsDirectory(); File(join("$directory/output_file_name.xlsx")) ..createSync(recursive: true) ..writeAsBytesSync(fileBytes);
join报错需要添加import 'package:path/path.dart' show join;
总结
完了,不懂的评论再回复
来源地址:https://blog.csdn.net/weixin_56924782/article/details/129010414