Flutter中按列读取Excel数据并提取姓名与邮箱
Excel按列读取并提取姓名、邮箱数据
我目前使用excel: ^2.0.1包结合FilePicker选择文件读取Excel数据,已经实现按行读取每个单元格的功能,代码如下:
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()); }); } } } }
现在需要实现按列读取数据,并且用户上传的Excel可能包含多个表头,我只需要提取其中的姓名和邮箱信息,存入以下类:
class ExcelSheetData { var name; var email; ExcelSheetData({this.name, this.email}); }
附示例Excel表结构:
解决方案
1. 按列读取数据的基础逻辑
excel包的Sheet类提供了col(int columnIndex)方法,可以直接获取指定列的所有单元格。示例代码:
// 遍历第0列所有行 sheetObject.col(0).forEach((cell) { print(cell.value?.toString() ?? '空单元格'); });
2. 提取姓名和邮箱的完整实现
由于Excel可能有自定义表头,核心思路是先遍历表头行,定位姓名、邮箱对应的列索引,再逐行提取对应列的数据:
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); List<ExcelSheetData> dataList = []; for (var table in excel.tables.keys) { Sheet sheetObject = excel[table]; int nameColIndex = -1; int emailColIndex = -1; // 遍历表头行(假设表头在第0行,可根据实际调整) var headerRow = sheetObject.row(0); for (int col = 0; col < headerRow.length; col++) { var cellValue = headerRow[col]?.value?.toString()?.trim(); if (cellValue == '姓名') { // 匹配姓名表头 nameColIndex = col; } else if (cellValue == '邮箱') { // 匹配邮箱表头 emailColIndex = col; } } // 找到目标列后提取数据 if (nameColIndex != -1 && emailColIndex != -1) { // 从第1行开始遍历数据行(跳过表头) for (int row = 1; row < sheetObject.maxRows; row++) { var currentRow = sheetObject.row(row); // 避免单元格不存在导致的异常 var name = currentRow.length > nameColIndex ? currentRow[nameColIndex]?.value : null; var email = currentRow.length > emailColIndex ? currentRow[emailColIndex]?.value : null; // 过滤空数据(可选) if (name != null || email != null) { dataList.add(ExcelSheetData(name: name, email: email)); } } } } // 打印提取结果 dataList.forEach((data) { print('姓名:${data.name},邮箱:${data.email}'); }); } }
补充说明
- 表头行调整:如果Excel表头不在第0行,修改
row(0)为对应行号即可。 - 表头匹配优化:可根据实际需求调整匹配规则,比如忽略大小写(
cellValue?.toLowerCase() == '姓名')、匹配关键词(cellValue?.contains('姓名'))。 - 空值处理:代码中加入了空值判断,避免因单元格为空或行长度不足导致的异常。
内容的提问来源于stack exchange,提问作者Muzammil Hassan
相关产品推荐
相关产品推荐

