how to convert excel sheet into json in flutter.
I have a excel sheet of students names and classes and i want to convert it to json to make it easy to run the app or another way to upload date to 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;}
I want to learn how to use this script in my application or another way is more easy and simple
Thanks
Use this methods:
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);
}
Updated your code just a bit....
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;
}
Related
I had this list but since i add lazy loading function,my sorting fuction stoped working.
here is some of the code and sort function is on top:
I had this list but since i add lazy loading function,my sorting fuction stoped working.
here is some of the code and sort function is on top:
I had this list but since i add lazy loading function,my sorting fuction stoped working.
here is some of the code and sort function is on top:
void showEvsePanels() async{
tempEvses.sort((a, b) {
int nameComp = a.sort_availability.compareTo(b.sort_availability);
if (nameComp == stationAvailability.available.index) {
return a.distance.compareTo(b.distance); // '-' for descending
}
return nameComp;
});
setState(() {
if (evseSearchField.isEmpty){
int i = 0;
if (tempEvses.length != 0){
evsePanels.clear();
while (i < tempEvses.length){
evsePanels.add(new EvsePanel(tempEvses[i], widget.appController, false));
i++;
}
}
}
else{
int i = 0;
if (tempEvses.length != 0){
evsePanels.clear();
while (i < tempEvses.length){
if (containsIgnoreCase(tempEvses[i].friendlyName, evseSearchField))
evsePanels.add(new EvsePanel(
tempEvses[i], widget.appController, false));
i++;
}
}
}
});
}
List<Evse> tempEvses = [];
Future fetch() async {
if (isLoading) return;
isLoading = true;
const limit = 10;
final url = Uri.parse('https://everywhere-dev.iccs.gr:18083/evse/getEvsesPaged?page=$page&pageLimit=$limit');
final response = await http.get(url);
if (response.statusCode == 200) {
final List newItems = json.decode(response.body)["results"];
setState(() {
page++;
isLoading = false;
if (newItems.length <limit) {
hasMore = false;
}
tempEvses.addAll(newItems.map<Evse>((items) {
final evseID = items['evseID'];
final friendlyName = items['friendlyName'];
final street = items['street'];
final streetNumber = items['streetNumber'];
final region = items['region'];
final lat = items['lat'] ?? 0.0;
final lng = items['lng'] ?? 0.0;
final connectorList = items['connectorList'];
final cpSerial = items['cpSerial'];
final img = items['img'];
return new Evse(evseID: evseID, friendlyName: friendlyName, street: street, streetNumber: streetNumber, region: region, lat: lat, lng: lng, connectorList: [connectorList], cpSerial: cpSerial, img: img);
}).toList());
for(int i=0 ; i<tempEvses.length; i++ ){
this.tempEvses[i].calculateDistance(widget.appController.currentLocation);
// this.tempEvses[i].calculateAvailability();
this.tempEvses[i].isEvseFavorite(widget.appController.favoritesList);
this.tempEvses[i].storePlugCounters();
}
showEvsePanels();
});
}
}
I'm trying to upload multiple images in backend.
I got this response when I'm trying to print files:
[Instance of 'MultipartFile', Instance of 'MultipartFile', Instance of 'MultipartFile']
but at a server side I got null array {}. This is my method. I'm using http for api communication.
Future<Map<String, dynamic>> postWithMultiImage(
String _url,
Map<String, String> _headers,
Map<String, String> _params,
String _imageKey,
List _imageFile) async {
if (_headers != null) {
print('_headers => $_headers');
}
print('_params => $_params');
print('_url => $_url');
var request = http.MultipartRequest("POST", Uri.parse(BASE_URL + _url));
if (_headers != null) {
request.headers.addAll(_headers);
}
if (_params != null) {
request.fields.addAll(_params);
}
if (_imageFile != null) {
for (int i = 0; i < _imageFile.length; i++) {
final _type = lookupMimeType(_imageFile[i]);
final _name =
'${DateTime.now().toIso8601String()}.${_type.split('/').last}';
final _partFile = http.MultipartFile(
_imageKey,
File(_imageFile[i]).openRead(),
File(_imageFile[i]).lengthSync(),
filename: _name);
request.files.add(_partFile);
}
print('request files: ${request.files}');
}
var response = await request.send();
final code = response.statusCode;
print('response code => $code');
final responseBody = await http.Response.fromStream(response);
final body = responseBody.body;
final jsonBody = json.decode(body);
Map<String, dynamic> _resDic;
if (code == 200) {
_resDic = Map<String, dynamic>.from(jsonBody);
_resDic[STATUS] = _resDic[SUCCESS] == 1;
} else {
_resDic = Map<String, dynamic>();
_resDic[STATUS] = false;
_resDic[IS_TOKEN_EXPIRED] = 0;
_resDic[MESSAGE] = jsonBody[MESSAGE] != null
? jsonBody[MESSAGE]
: 'Something went wrong';
}
_resDic[HTTP_CODE] = code;
return _resDic;
}
Thanks in advance.
You can try >>THIS<<
I am new with flutter having issues with the future functions. I had a single await function on other screen and its returning list but when I use multiple await function in a single future function it returns an empty list and executes before many other await functions to execute. My Question is why my future functions are returning an empty list I had tried almost everything on the internet please help
Future<List<AllShefz>> getAllShefz() async {
List<AllShefz> allShefz = [];
var data = await FirebaseDatabase.instance
.reference()
.child("Resturants")
.once()
.then((DataSnapshot datasnapshot) async {
if (datasnapshot != null) {
Map<dynamic, dynamic> values = await datasnapshot.value;
values.forEach((key, value) async {
await FirebaseDatabase.instance
.reference()
.child("Resturants")
.child(key)
.child("Profile")
.once()
.then((DataSnapshot snapshot) async {
print(" I am here");
Map<dynamic, dynamic> newvals = await snapshot.value;
var position, name, gender, status;
if (await snapshot.value != null) {
position = await newvals["Position"];
name = await newvals["Name"];
gender = await newvals["Gender"];
status = await newvals["Status"];
if (position != null && status == "Approaved") {
var arr = ltlnClass().getSplit(position);
String latStr = arr[0];
String lngStr = arr[1];
String myPosition;
await new MyLocation()
.getMyLocation()
.then((value) => {myPosition = value.toString()});
var arr2 = ltlnClass().getSplit(myPosition);
String latStr2 = arr2[0];
String lngStr2 = arr2[1];
double lat2 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(latStr), latStr));
double lng2 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(lngStr), lngStr));
double lat1 = double.parse(ltlnClass()
.getLtlng(ltlnClass().getIndex(latStr2), latStr2));
double lng1 = double.parse(ltlnClass()
.getLtlng(ltlnClass().getIndex(lngStr2), lngStr2));
double distance =
DistanceCalculator().distance(lat1, lat2, lng1, lng2);
print("Lng 1" + lng1.toString());
print("Lng 2" + lng2.toString());
print("Lat 1" + lat1.toString());
print("Lat 2" + lat2.toString());
print("Distance is " + distance.toString());
AllShefz myShef =
new AllShefz(key, position, distance, gender, name, status);
setState(() {
allShefz.add(myShef);
});
}
}
return allShefz;
});
});
} else {
print("Null value found");
}
});
return allShefz;
}
```.
You seem to be mixing .then and await calls. That is possible, but extremely error-prone for beginners (and frankly even experts if they did not have the correct dose of caffeine yet).
I suggest you remove all .then continuations and replace them with await. That way you can properly debug your code and find out where you missed out on waiting for a async call. Your indentation level should shrink to something manageable and you will be able to find the mistake easily.
As #nvoigt mentioned, you should change your code. Now you can easily debug your result step by step.
Future<List<AllShefz>> getAllShefz() async {
List<AllShefz> allShefz = [];
var datasnapshot =
await FirebaseDatabase.instance.reference().child("Resturants").once();
if (datasnapshot != null) {
Map<dynamic, dynamic> values = await datasnapshot.value;
values.forEach((key, value) async {
var snapshot = await FirebaseDatabase.instance
.reference()
.child("Resturants")
.child(key)
.child("Profile")
.once();
print(" I am here");
Map<dynamic, dynamic> newvals = await snapshot.value;
var position, name, gender, status;
if (await snapshot.value != null) {
position = await newvals["Position"];
name = await newvals["Name"];
gender = await newvals["Gender"];
status = await newvals["Status"];
if (position != null && status == "Approaved") {
var arr = ltlnClass().getSplit(position);
String latStr = arr[0];
String lngStr = arr[1];
String myPosition;
var value = await new MyLocation().getMyLocation();
myPosition = value.toString();
var arr2 = ltlnClass().getSplit(myPosition);
String latStr2 = arr2[0];
String lngStr2 = arr2[1];
double lat2 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(latStr), latStr));
double lng2 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(lngStr), lngStr));
double lat1 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(latStr2), latStr2));
double lng1 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(lngStr2), lngStr2));
double distance =
DistanceCalculator().distance(lat1, lat2, lng1, lng2);
print("Lng 1" + lng1.toString());
print("Lng 2" + lng2.toString());
print("Lat 1" + lat1.toString());
print("Lat 2" + lat2.toString());
print("Distance is " + distance.toString());
AllShefz myShef =
new AllShefz(key, position, distance, gender, name, status);
setState(() {
allShefz.add(myShef);
});
}
}
return allShefz;
});
} else {
print("Null value found");
}
return allShefz;
}
I have search screen where i can serach text it will returns data like json below,but when i try to parse data it's not working i am getting data upto this line of codevar data = menu_list[i];,but when i pass data to model,it's not quite working,any idea what went wrong
Retrieve json from api function
Future<String> GetSearchdata(String search_text) async {
ProgressDialog dialog = CustomDialogs().showLoadingProgressDialog(context);
var response = await http.post(Urls.SEARCH_ALL,
headers: {"Content-Type": "application/json", "Authorization": token},
body: json.encode({"searchText": search_text, "language": "english"}));
Map<String, dynamic> value = json.decode(response.body);
var status = value['status'];
var msg_response = value['message'];
if (response.statusCode == 200) {
dialog.dismissProgressDialog(context);
if (status == true) {
var menu_list = value['doc'];
if(menu_list.length>0)
{
for (int i = 0; i < menu_list.length; i++) {
var data = menu_list[i];
_searchResult.add(SearchModel.fromJson(data));
}
setState(() {
print("UI Updated");
});
}
else{
final snackBar = SnackBar(content: Text("No data available"));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
}
Model
class SearchModel {
String id = "";
String name = "";
String category_name = "";
SearchModel({
this.id,
this.name,
this.category_name,
});
SearchModel.fromJson(json)
: id = json['_id'].toString(),
name = json['registrations']['name'].toString(),
category_name =json['category']['name'].toString();
}
Json
{
"status":true,
"doc":{
"registrations":[
{
"_id":"5f44b5aafc77a977e88f558c",
"name":"test shop",
"category":[
{
"name":"/Furnitue Shop"
}
]
},
{
"_id":"5f44bd1b52977b4d1411f281",
"name":"test1",
"category":[
{
"name":"/Painting"
}
]
}
]
}
}
Try my code below :
Model
class SearchModel {
String id = "";
String name = "";
String category_name = "";
SearchModel({
this.id,
this.name,
this.category_name,
});
SearchModel.fromJson(json)
: id = json['_id'].toString(),
name = json['name'].toString(),
category_name = json['category'][0]['name'].toString();
}
Retrieve json
if (response.statusCode == 200) {
dialog.dismissProgressDialog(context);
if (status == true) {
var menu_list = value['doc']["registrations"];
if(menu_list.length>0)
{
final List<SearchModel> listFromJson = menu_list.map<SearchModel>((item) => SearchModel.fromJson(item)).toList();
setState(() {
_searchResult = listFromJson;
print("UI Updated");
});
}
else{
final snackBar = SnackBar(content: Text("No data available"));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
final snackBar = SnackBar(content: Text(msg_response));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
Few discoveries:
1.
var menu_list = value['doc'];
This should not be
var menu_list = value['doc']['registrations'];
instead? The registrations is your list, not the doc.
2.
After you access the right element, then your model should look like this:
SearchModel.fromJson(json):
id = json['_id'].toString(),
name = json['name'].toString(),
category_name =json['category']['name'].toString();
Do note, that your category is list again (I don't know if it is intended), but if it is, then first you need to get each element from you category list and get the name of those.
Or you need something like this, if you have only 1 element there:
category_name =json['category'][0]['name'].toString();
I have a folder with csv files. For now I have to go manually and write manually each file. Is it somehow to get all the files and do a for loop? This is the current code I have and thank you so much!
static List<Widget> getPlates(String file) {
List<Widget> listWidgets = [];
loadAsset('assets/$file.csv').then((dynamic output) {
List<String> list = output.split('\n');
for (int i = 1; i < list.length - 1; i++) {
List<String> sublist = list[i].split(';');
listWidgets.add(CardPlate(
name: sublist[0],
ingredients: sublist[1],
price: sublist[2],
));
}
});
return listWidgets;
}
static Future<String> loadAsset(String path) async {
return await rootBundle.loadString(path);
}
Are you talking something like this, or even more indepth?
output.split('\n').forEach((String entry) {
List<String> sublist = entry.split(';');
listWidgets.add(CardPlate(
name: sublist[0],
ingredients: sublist[1],
price: sublist[2],
));
})
import 'dart:convert';
static final reg = RegExp(r'assets/\w+\.csv'); //check for all files within assets, not including subfolders
static List<Widget> getPlater() async{
List<Widget> listWidgets = [];
var myAssets = await rootBundle.loadString('AssetManifest.json'); //file generated by flutter which you can read up through the default bundle
Map<String, dynamic> map = json.decode(myAssets);
map.removeWhere((key, value) => !key.contains(reg)); //remove all keys that aren't csv files
for(String path in map.keys){
var output = await rootBundle.loadString(path);
List<String> list = output.split('\n');
for (int i = 1; i < list.length - 1; i++) {
List<String> sublist = list[i].split(';');
listWidgets.add(CardPlate(
name: sublist[0],
ingredients: sublist[1],
price: sublist[2],
));
}
}
return listWidgets;
}