如何在flutter中将excel表格转换为json。
我有一张包含学生姓名和班级的 Excel 表,我想将其转换为 json,以便轻松运行应用程序或以其他方式将日期上传到 firestore。
Future<String> excelToJson() async {
var file = await FilePicker.getFilePath(
type: FileType.custom, allowedExtensions: ['xlsx', 'csv', 'xls']);
var bytes = File(file).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
int i = 0;
List<dynamic> keys = new List<dynamic>();
List<Map<String, dynamic>> json = new List<Map<String, dynamic>>();
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
if (i == 0) {
keys = row;
i++;
} else {
Map<String, dynamic> temp = Map<String, dynamic>();
int j = 0;
String tk = '';
for (var key in keys) {
tk = "\u201C" + key + "\u201D";
temp[tk] = (row[j].runtimeType==String)?"\u201C" + row[j].toString() + "\u201D":row[j];
j++;
}
json.add(temp);
}
}
}
print(json.length);
String fullJson = json.toString().substring(1, json.toString().length - 1);
return fullJson;}
我想学习如何在我的应用程序中使用这个脚本,或者其他方式更容易和简单
谢谢
使用此方法:
Future<void> excelToJson(String fileName, String fileDirectory,GlobalKey<ScaffoldState> scaffoldKey) async {
ByteData data = await rootBundle.load(fileDirectory);
var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
var excel = Excel.decodeBytes(bytes);
int i = 0;
List<dynamic> keys = new List<dynamic>();
List<Map<String, dynamic>> json = new List<Map<String, dynamic>>();
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
if (i == 0) {
keys = row;
i++;
} else {
Map<String, dynamic> temp = Map<String, dynamic>();
int j = 0;
String tk = '';
for (var key in keys) {
tk = '"' + key + '"';
temp[tk] = (row[j].runtimeType == String)
? '"' + row[j].toString() + '"'
: row[j];
j++;
}
json.add(temp);
}
}
}
print(json.length);
String fullJson = json.toString().substring(1, json
.toString()
.length - 1);
fullJson = '{ "DATA" : [$fullJson]}';
final directory = await getExternalStorageDirectory();
File file = await File('${directory.path}/$fileName.json').create();
await file.writeAsString(fullJson).then((value) =>
scaffoldKey.currentState
.showSnackBar(SnackBar(content: Text("Completed")))
);
print(file.exists().toString());
}
Future<void> jsonToExcel(String fileName, String fileDirectory,GlobalKey<ScaffoldState> scaffoldKey) async{
String jsonString = await rootBundle.loadString(fileDirectory);
List<dynamic> jsonResult = jsonDecode(jsonString)["DATA"];
var excel = Excel.createExcel();
Sheet sheetObject = excel['Sheet1'];
Map<String,dynamic> result = jsonResult[0];
sheetObject.appendRow(result.keys.toList());
for(int i =0;i<jsonResult.length;i++){
Map<String,dynamic> result = jsonResult[i];
sheetObject.appendRow(result.values.toList());
}
final directory = await getExternalStorageDirectory();
excel.encode().then((onValue) {
File(("${directory.path}/$fileName.xlsx"))
..createSync(recursive: true)
..writeAsBytesSync(onValue);
scaffoldKey.currentState
.showSnackBar(SnackBar(content: Text("Completed")));
});
print(sheetObject);
}
稍微更新了您的代码......
Future<String> excelToJson() async {
FilePickerResult result =await FilePicker.platform.pickFiles(type:FileType.custom,allowedExtensions: ['xls','xlsx','csv']);
if (result != null) {
File excelFile = File(result.files.single.path);}
var bytes = File(excelFilePath).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
int i = 0;
List<dynamic> keys = [];
var jsonMap = [];
for (var table in excel.tables.keys) {
dev.log(table.toString());
for (var row in excel.tables[table].rows) {
dev.log(row.toString());
if (i == 0) {
keys = row;
i++;
} else {
var temp = {};
int j = 0;
String tk = '';
for (var key in keys) {
tk = '\"${key.toString()}\"';
temp[tk] = (row[j].runtimeType == String)
? '\"${row[j].toString()}\"'
: row[j];
j++;
}
jsonMap.add(temp);
}
}
}
dev.log(
jsonMap.length.toString(),
name: 'excel to json',
);
dev.log(jsonMap.toString(), name: 'excel to json');
String fullJson =
jsonMap.toString().substring(1, jsonMap.toString().length - 1);
dev.log(
fullJson.toString(),
name: 'excel to json',
);
return fullJson;
}
一般我有两种方法
从内部存储中选择Excel文件 (您可以从任何地方获取,仅限 xlsx 格式)
制作第二种从Excel文件获取列表的方法
How this will work
Here we used PlugIn : [Excel][1]
First get file (excel) from byte ( Uint8List ) format
Then Make logic for get data from sheet and convert into json
After create json/map we store in list and return from method
注意 这里将创建地图,其键取自表标题(第一行)
选择Excel
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
Future<Uint8List?> pickExcelCsv({
String pickTitle = "Pick File",
}) async {
final picker = FilePicker.platform;
final FilePickerResult? result = await picker.pickFiles(
allowCompression: false,
allowMultiple: false,
allowedExtensions: [
'xlsx',
'csv',
],
type: FileType.custom,
dialogTitle: pickTitle,
);
if (result != null) {
return result.files.first.bytes;
}
return null;
}
getJson/列表
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_excel/excel.dart';
List<Map<String, dynamic>> extractDataFromExcel({required Uint8List bytes}) {
Excel excel = Excel.decodeBytes(bytes);
final List<Map<String, dynamic>> result = [];
final Map<String, dynamic> createMap = {};
final keys = <String>[];
// get data from first sheet
final int n = excel.tables[excel.tables.keys.first]?.rows.length ?? 0;
debugPrint('n => $n');
// final List<Data?> rows in excel.tables[excel.tables.keys.first]!.rows
for (int i = 0; i < n; i++) {
final rows = excel.tables[excel.tables.keys.first]!.rows[i];
for (int j = 0; j < rows.length; j++) {
// index = 0 it will show an header of sheet
final row = rows[j];
// Create Header(Keys) for map
if (i == 0 && row != null) {
// get header/key from excel and make it list
keys.add('${row.value}'); // Store key as string
// Default value is empty
createMap['${row.value}'] = "";
}
// add value in map
else if (i > 0 && row != null) {
createMap[keys[j]] = row.value;
}
}
// Now We have make ready
// we have multiple map/json
// we we can make list of map/json
// we add map have key and value both => add if i!=0
if (i != 0) result.add(Map<String, dynamic>.from(createMap));
}
return result;
}
使用
onTap: () async {
final bytes = await pickExcelCsv();
if (bytes != null) {
final result = extractDataFromExcel(bytes: bytes);
debugPrint('### -> $result');
}
},
结果
和列表
[
{
SrNo: 1,
FirstName: Dulce,
LastName: Abril,
Gender: Female,
Country: UnitedStates,
Age: 32,
Date: 15/10/2017,
ID: 1562
},
{
SrNo: 2,
FirstName: Mara,
LastName: Hashimoto,
Gender: Female,
Country: GreatBritain,
Age: 25,
Date: 16/08/2016,
ID: 1582
},
{
SrNo: 3,
FirstName: Philip,
LastName: Gent,
Gender: Male,
Country: France,
Age: 36,
Date: 21/05/2015,
ID: 2587
},
{
SrNo: 4,
FirstName: Kathleen,
LastName: Hanner,
Gender: Female,
Country: UnitedStates,
Age: 25,
Date: 15/10/2017,
ID: 3549
},
{
SrNo: 5,
FirstName: Nereida,
LastName: Magwood,
Gender: Female,
Country: UnitedStates,
Age: 58,
Date: 16/08/2016,
ID: 2468
},
{
SrNo: 6,
FirstName: Gaston,
LastName: Brumm,
Gender: Male,
Country: UnitedStates,
Age: 24,
Date: 21/05/2015,
ID: 2554
},
{
SrNo: 7,
FirstName: Etta,
LastName: Hurn,
Gender: Female,
Country: GreatBritain,
Age: 56,
Date: 15/10/2017,
ID: 3598
},
{
SrNo: 8,
FirstName: Earlean,
LastName: Melgar,
Gender: Female,
Country: UnitedStates,
Age: 27,
Date: 16/08/2016,
ID: 2456
},
{
SrNo: 9,
FirstName: Vincenza,
LastName: Weiland,
Gender: Female,
Country: UnitedStates,
Age: 40,
Date: 21/05/2015,
ID: 6548
}
]
希望这对你有帮助!!!