I am Using excel: ^2.0.1
for reading data from my file picked with File Picker. I am able to Read each cell by
void getExcelFile() async {
FilePickerResult pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
allowMultiple: false,
);
if (pickedFile != null) {
var file = pickedFile.paths.single;
var bytes = await File(file).readAsBytes();
Excel excel = await compute(parseExcelFile, bytes);
for (var table in excel.tables.keys) {
print(table);
print(excel.tables[table].maxCols);
print(excel.tables[table].maxRows);
Sheet sheetObject = excel[table];
for (int row = 0; row < sheetObject.maxRows; row++) {
sheetObject.row(row).forEach((cell) {
var val = cell.value; // Value stored in the particular cell
print("cell value is: " + val.toString());
});
}
}
}
}
but data is row wise, I want to read Data Column Wise
here I want to add each name with its corresponding email into my class, user can add his own excel file and there could be several headings in that file but i just need name and email
class ExcelSheetData {
var name;
var email;
ExcelSheetData({this.name, this.email});
}
I was able to find round about for column index of name and email then I was able to get name and email from each row from that particular index, below is the code if it help someone other:
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;
}