phpspredsheet導出excel,支持長數字

工作中比較多地遇到導出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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章