Reputation: 197
Is it possible to fetch the data existing in a file.xlsx using Excel
dependency by columns?
I mean for each column that exist in the sheet it should be stored in a list for example.
I have only found how to fetch data by rows using:
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// code
}
}
Is there any way to do this by columns?
Thank you.
Upvotes: 2
Views: 1511
Reputation: 496
Found a temporary solution, downside is that you need to get column heading(s) for getting their values, below is the code if it helps you out:
Future<List<ExcelSheetData>> getExcelFile(BuildContext context, String name, String email) async {
FilePickerResult pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
allowMultiple: false,
);
List<ExcelSheetData> excelList = [];
int nameIndex;
int emailIndex;
if (pickedFile != null) {
setAddMembersLoadingTrue();
var file = pickedFile.paths.single;
var bytes = await File(file).readAsBytes();
Excel excel = await compute(parseExcelFile, bytes);
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// name variable is for Name of Column Heading for Name
if (row?.any((element) => element?.value?.toString() == name) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == name);
nameIndex = data.colIndex;
}
// email variable is for Name of Column Heading for Email
if (row?.any((element) => element?.value?.toString() == email) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == email);
emailIndex = data.colIndex;
}
if (nameIndex != null && emailIndex != null) {
if (row[nameIndex]?.value.toString().toLowerCase() != name.toLowerCase() && row[emailIndex]?.value.toString().toLowerCase() != email.toLowerCase())
excelList.add(
ExcelSheetData(
name: row[nameIndex]?.value.toString(),
email: row[emailIndex]?.value.toString(),
),
);
}
}
}
setAddMembersLoadingFalse();
return excelList;
}
return null;
}
refer to this question if you need more clarification
Upvotes: 0
Reputation: 7150
I think this code from example is you need:
/// Iterating and changing values to desired type
for (int row = 0; row < sheet.maxRows; row++) {
sheet.row(row).forEach((cell) {
var val = cell.value; // Value stored in the particular cell
});
}
Upvotes: 2