Reading spreadsheet using PHPExcel

前端 未结 2 1985
囚心锁ツ
囚心锁ツ 2021-02-08 19:34

I\'m trying to upload a spreadsheet and read it into a MySQL database using PHPExcel.

For .xlsx files it works fine but whenever I try to upload a .ods file it throws th

相关标签:
2条回答
  • 2021-02-08 20:05

    When a file is uploaded to your webserver, The file will be saved in the temporary folder of your system with a random name.

    What you were trying to do was giving the actual name of the file you uploaded, But since the file was created with a random name in the tmp folder. You will need to use tmp_name instead, Which actually point the that random named file.

    Also note, in name You only have the name of the file that was uploaded and not the path, But with tmp_name you have the actual path to the file.

    See the following example of a file upload you would get.

    array(
     [UploadFieldName]=>array(
        [name] => MyFile.jpg
        [type] => image/jpeg
        [tmp_name] => /tmp/php/php6hst32
        [error] => UPLOAD_ERR_OK
        [size] => 98174
      )
    )
    

    change your code to this instead

     //Check valid spreadsheet has been uploaded
    if(isset($_FILES['spreadsheet'])){
    if($_FILES['spreadsheet']['tmp_name']){
    if(!$_FILES['spreadsheet']['error'])
    {
    
        $inputFile = $_FILES['spreadsheet']['tmp_name'];
        $extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
        if($extension == 'XLSX' || $extension == 'ODS'){
    
            //Read spreadsheeet workbook
            try {
                 $inputFileType = PHPExcel_IOFactory::identify($inputFile);
                 $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                     $objPHPExcel = $objReader->load($inputFile);
            } catch(Exception $e) {
                    die($e->getMessage());
            }
    
            //Get worksheet dimensions
            $sheet = $objPHPExcel->getSheet(0); 
            $highestRow = $sheet->getHighestRow(); 
            $highestColumn = $sheet->getHighestColumn();
    
            //Loop through each row of the worksheet in turn
            for ($row = 1; $row <= $highestRow; $row++){ 
                    //  Read a row of data into an array
                    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                    //Insert into database
            }
        }
        else{
            echo "Please upload an XLSX or ODS file";
        }
    }
    else{
        echo $_FILES['spreadsheet']['error'];
    }
    }
    }
    
    ?>
    
    0 讨论(0)
  • 2021-02-08 20:06

    In my case there was an error detecting the extension in this line

    $extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
    

    if you need to solve just check from the name parameter

    $extension = strtoupper(explode(".", $_FILES['spreadsheet']['name'])[1]);
    

    The rest is working thanks :)

    0 讨论(0)
提交回复
热议问题