phpspredsheet匯出excel,支援長數字
阿新 • • 發佈:2020-12-25
工作中比較多地遇到匯出excel的需求,我通常是用phpspread完成,然而有時候像匯出身份證號,銀行卡號,訂單號這些比較長而且格式為純數字的資料時往往會出現變成科學計數法的情況,設定為預設文字格式又會出現末尾數字變成0的情況
經過搜尋和測試後總算是有了解決辦法,我將其封裝成了一個函式
function CreateExcel($Data, $Header, $Path, $FileName,$LongNumberField=null) { $SpreadSheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $Sheet = $SpreadSheet->getActiveSheet(); if($LongNumberField===null){ array_unshift($Data, $Header); $SpreadSheet->getDefaultStyle()->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER); $Sheet->fromArray($Data); } else{ $HeaderCount=count($Header); for($i=0;$i<$HeaderCount;$i++){ $Sheet->setCellValueByColumnAndRow($i+1,1,$Header[$i]); } $RowIndex=2; $DataCount=count($Data); for($i=0;$i<$DataCount;$i++){ $ColumnIndex=1; foreach ($Data[$i] as $Key=>$Value){ if(in_array($Key,$LongNumberField)){ $Sheet->setCellValueExplicitByColumnAndRow($ColumnIndex,$RowIndex,$Value,\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING); } else{ $Sheet->setCellValueByColumnAndRow($ColumnIndex,$RowIndex,$Value); } $ColumnIndex++; } $RowIndex++; } } $Xlsx = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($SpreadSheet); $Xlsx->save($Path . $FileName); }
示例
$Data=[ ['id'=>1,'name'=>'張三','bank_card'=>'123456789123456789'], ['id'=>2,'name'=>'李四','bank_card'=>'123456123456789789'], ]; $Header=['id','姓名','銀行卡號']; $Path='D:/www/test/'; $FileName='Export.xlsx'; $LongNumberField=['bank_card']; CreateExcel($Data,$Header,$Path,$FileName,$LongNumberField);