• phpspredsheet导出excel,支持长数字


    工作中比较多地遇到导出excel的需求,我通常是用phpspread完成,然而有时候像导出身份证号,银行卡号,订单号这些比较长而且格式为纯数字的数据时往往会出现变成科学计数法的情况,设置为默认文本格式又会出现末尾数字变成0的情况

    经过搜索和测试后总算是有了解决办法,我将其封装成了一个函数:

    function CreateExcel($Data, $Header, $Path, $FileName,$LongNumberField=null)
    {
        $SpreadSheet = new PhpOfficePhpSpreadsheetSpreadsheet();
        $Sheet = $SpreadSheet->getActiveSheet();
        if($LongNumberField===null){
            array_unshift($Data, $Header);
            $SpreadSheet->getDefaultStyle()->getNumberFormat()->setFormatCode(PhpOfficePhpSpreadsheetStyleNumberFormat::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,PhpOfficePhpSpreadsheetCellDataType::TYPE_STRING);
                    }
                    else{
                        $Sheet->setCellValueByColumnAndRow($ColumnIndex,$RowIndex,$Value);
                    }
                    $ColumnIndex++;
                }
                $RowIndex++;
            }
        }
        $Xlsx = new PhpOfficePhpSpreadsheetWriterXlsx($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);
    

      

  • 相关阅读:
    sonarque下载和安装使用
    npm install appium
    WIn10 电脑运行Docker
    AngularJs Type error : Cannot read property 'childNodes' of undefined
    Angular ui-route介绍
    Thymeleaf的模板使用介绍
    IntelliJ IDEA IDEA 2018 激活注册码
    session和cookies
    springmvc中的拦截器interceptor用法
    实现mapper接口注入的两种方式,以及后台的使用区别
  • 原文地址:https://www.cnblogs.com/doseoer/p/14842491.html
Copyright © 2020-2023  润新知