Laravel Excel导入时如何获取真实数字值?
解决Laravel Excel导入长数字变成科学计数法的问题
我之前踩过这个一模一样的坑!Laravel Excel处理长数字时默认会转成科学计数法,你用的setColumnFormat(["A" => "@"])其实是导出时用来设置单元格格式的,导入阶段根本不会生效,难怪没效果😂
下面分两种场景给你解决方案:
一、如果你还在使用老版本Laravel Excel(依赖Excel::load方法)
直接操作底层的PhpSpreadsheet对象,强制将目标列按文本类型读取,修改你的代码如下:
$data['excel'] = Excel::load($path, function ($reader) { $reader->sheet(0, function ($sheet) { // 获取PhpSpreadsheet的原生工作表对象 $phpSheet = $sheet->getDelegate(); // 方案1:直接设置A列为文本格式 $phpSheet->getStyle('A') ->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT); // 方案2(更稳妥):遍历单元格,强制将A列值转为字符串类型 foreach ($phpSheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); foreach ($cellIterator as $cell) { if ($cell->getColumn() === 'A') { // 获取单元格原始值,避免自动转成科学计数法 $rawValue = $cell->getRawValue(); // 强制设置为字符串类型 $cell->setValueExplicit($rawValue, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING); } } } }); })->toArray();
二、如果你使用的是Laravel Excel 3.0+(推荐用导入类的方式)
新版本官方已经弃用了Excel::load,更推荐用自定义导入类,通过WithCustomValueBinder来强制指定列按文本读取:
1. 创建导入类
namespace App\Imports; use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\ToCollection; use Maatwebsite\Excel\Concerns\WithHeadingRow; use PhpOffice\PhpSpreadsheet\Cell\Cell; use Maatwebsite\Excel\Concerns\WithCustomValueBinder; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder; class BigNumberImport extends DefaultValueBinder implements ToCollection, WithHeadingRow, WithCustomValueBinder { // 自定义值绑定规则:强制A列为文本类型 public function bindValue(Cell $cell, $value) { if ($cell->getColumn() === 'A') { $cell->setValueExplicit($value, DataType::TYPE_STRING); return true; } // 其他列沿用默认处理逻辑 return parent::bindValue($cell, $value); } // 处理读取到的数据集合 public function collection(Collection $rows) { foreach ($rows as $row) { // 这里的A列值已经是原始字符串了,比如"198610012009011005" $originalNumber = $row['对应表头名称']; // 替换成你A列的表头字段 // 后续业务逻辑处理... } } }
2. 在控制器中调用导入类
use App\Imports\BigNumberImport; use Maatwebsite\Excel\Facades\Excel; // ... Excel::import(new BigNumberImport, $path);
原理说明
长数字被转成科学计数法,本质是因为PhpSpreadsheet默认会把数字格式的单元格解析为float类型,当数字长度超过一定阈值时就会自动用科学计数法表示。我们的核心思路就是强制让PhpSpreadsheet把目标单元格按文本类型读取/存储,这样就能保留原始的数字字符串了。
内容的提问来源于stack exchange,提问作者Arie Pratama
相关产品推荐
相关产品推荐

