PhpOffice 将 excel 转换为 json

问题描述

我正在尝试使用 PHPOffice (PHPSpreadsheet) 库将 excel 文件转换为特定的 json 输出。 Excel 表格如下所示:

enter image description here

我希望实现这个 json_encode:

{
"As24 sheet": [
    {
        "Contract": "656203","Vehicle card": "0130","Driver card": "","Product": "03","Fuel type": "DIESEL","Volume": "92.00","Date": "20210316","Hour": "0355"
    },{
        "Contract": "656203","Vehicle card": "0211","Volume": "74.30","Hour": "0415"
    },"Vehicle card": "0197","Volume": "33.70","Hour": "0522"
    },"Vehicle card": "0104","Volume": "55.13","Hour": "0553"
    },"Vehicle card": "0066","Volume": "105.63","Hour": "0756"
    },"Vehicle card": "0167","Volume": "54.88","Hour": "0757"
    }
]

}

这是我当前的代码,但我无法将作为标题的第一行与每一列分组,就像上面的 json 示例一样。任何帮助将不胜感激。

<?PHP 
require_once("vendor/autoload.PHP"); 

/* Start to develop here. Best regards https://PHP-download.com/ */



$inputFileType = 'Xlsx';
$inputFileName = 'motorina.xlsx';

/**  Create a new Reader of the type defined in $inputFileType  **/
$reader = PHPOffice\PHPSpreadsheet\IOFactory::createReader($inputFileType);
/**  Advise the Reader that we only want to load cell data  **/
$reader->setReadDataOnly(true);
/**  Load $inputFileName to a Spreadsheet Object  **/
$spreadsheet = $reader->load($inputFileName);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null,true,true);
$worksheet = $spreadsheet->getSheet(0);//
// Get the highest row and column numbers referenced in the worksheet
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPOffice\PHPSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

$data = array();


for ($row = 2; $row <= $highestRow; ++$row) {
    for ($col = 1; $col <= $highestColumnIndex; ++$col) {
    
        $data[] = array(
        $worksheet->getCellByColumnAndRow($col,1)->getValue() => $worksheet->getCellByColumnAndRow($col,$row)->getValue()
        );
    }

}    

echo json_encode($data);

解决方法

您的数组组合错误,每次添加一对( label => value )。您希望在单个字典中包含一整行,并将该字典添加到您的 $data 中。

$data = array();

for ($row = 1; $row <= $highestRow; $row++) {
    $riga = array();
    for ($col = 1; $col <= $highestColumnIndex; $col++) {
        $riga[] = $worksheet->getCellByColumnAndRow($col,$row)->getValue();
    }
    if (1 === $row) {
        // Header row. Save it in "$keys".
        $keys = $riga;
        continue;
    }
    // This is not the first row; so it is a data row.
    // Transform $riga into a dictionary and add it to $data.
    $data[] = array_combine($keys,$riga);
}