maatwebsite/excel 3.0以上导出解决身份证号码等长数字显示科学计算法
本内容是根据官方文档理解测试记录,如有问题可以直接访问官方文档地址。
由于身份证号码,银行卡号,导出自动转换成了科学计数法,搜索了一些内容,都是一些说前面加逗号,或等号,或其他来,限定列内容。感觉还是挺不靠谱,所有通过查看官方文档,找到解决方法。
在使用导出excel时,设置了列格式还是无法解决身份证自动变更为数字科学计算法。通过查看官方文档,有自定义格式列的方法,测试效果可以实现。
方法一:检查列的格式
通过继承DefaultValueBinder类,重写bindValue列的格式判断,但如果列内容为数字,并且长度大于或等于10,将该列定义为字符串文本列。
namespace App\Exports; use PhpOffice\PhpSpreadsheet\Cell\Cell; use Maatwebsite\Excel\Concerns\ToModel; use PhpOffice\PhpSpreadsheet\Cell\DataType; use Maatwebsite\Excel\Concerns\WithCustomValueBinder; use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder; class UsersExport extends DefaultValueBinder implements WithCustomValueBinder { public function bindValue(Cell $cell, $value) { if (is_numeric($value) && strlen ($value) >= 10) { $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); return true; } // else return default behavior return parent::bindValue($cell, $value); } }
方法二:所有列定义为字符串文本列
继承StringValueBinder类,说明将本次导出excel的所有列都定义为字符串文本列,无需重写bindValue方法。
namespace App\Exports; use Maatwebsite\Excel\Concerns\WithCustomValueBinder; class UsersExport extends \PhpOffice\PhpSpreadsheet\Cell\StringValueBinder implements WithCustomValueBinder { }
方法三:配置定义默认导出都是文本列
在config/excel.php配置文件中,找到如下参数并修改,即将默认的列格式处理,都定义成以字符串文本格式。
'value_binder' => [ 'default' => Maatwebsite\Excel\DefaultValueBinder::class, ],
将default改成
PhpOffice\PhpSpreadsheet\Cell\StringValueBinder::class
设置格式化列,liunx下无效
设置格式化列,按理可以自动将列设置成文本列。测试效果不行,在window环境下可以自动正常变成文本列,但在liunx环境下无效,仍然显示数字科学计算法。
namespace App\Exports; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use Maatwebsite\Excel\Concerns\WithColumnFormatting; class InvoicesExport implements WithColumnFormatting { public function columnFormats(): array { return [ 'B' => NumberFormat::FORMAT_TEXT, 'C' => NumberFormat::FORMAT_TEXT, ]; } }
来源于: https://docs.laravel-excel.com/3.1/exports/custom-formatting-values.html#value-binder
本文作者: admin
本文链接: https://www.jianbaizhan.com/article/639
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!