上一篇博客介绍了文件选择器 file_picker 的用法,这一篇博文将介绍如何读取 excel 文件。
需要明确的是,Flutter 本身没有提供读取 excel 的组件,所以我们采用了社区的开源解决方案——excel。
不过,写作这篇博客时的最新版(4.0.4)有一个 bug,读取 Mac Numbers 和 WPS 创建的 *.xlsx 文件时会抛出如下异常:
_Exception (Exception: custom numFmtId starts at 164 but found a value of 41), error happens when I read an excel file using flutter excel package
针对这个问题,有人已经提了 issue,作者暂时还没解决,文章最后我会给出一个临时解决方案。
首先,新建一个页面,中间放置一个 ElevatedButton,用于读取本地 excel 文件。
然后,给按钮增加点击事件处理方法:
ElevatedButton(
onPressed: () {
// _pickExcelFile();
_pickExcelFile();
},
child: const Text('Import'),
),
其中 _pickExcelFile
方法的实现如下:
_pickExcelFile() async {
// 选择文件
FilePickerResult? pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
allowMultiple: false,