将对象数组添加到PHPExcel模板

问题描述 投票:0回答:1

我正在从我的数据库中提取一个对象数组,目的是每个对象代表PHPExcel模板中的一行。数据如下:

[
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
]

我的Excel工作表中的行从17开始 - 因此第一个对象将在第17行输入,数组中的第二个对象将在第18行输入,依此类推。但是,我希望添加的列不是彼此相邻的,因此很难循环。例如,第一个对象的名称字段应输入C17,而年龄字段应输入F17,而other_info字段应输入J17,my_info应输入L17。然后将第二个对象输入相同的列,但输入下一行,依此类推。

我已经尝试循环遍历数组,但这不允许我跳过列,只添加到连续的列和行;

foreach ($array as $rowArray) {
    $columnID = 'C';
    $rowID = 17;
    foreach ($rowArray as $columnValue) {
        $objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
        $rowID++;
    } 
}

谁能给我一些指导呢?非常感激!

php arrays loops object phpexcel
1个回答
1
投票

试试这个:

$json = '[
            {
                "name": "name1",
                "age":"age1",
                "other_info":"other_info1",
                "my_info":"my_info1"
            },
            {
                "name": "name2",
                "age": "age2",
                "other_info": "other_info2",
                "my_info": "my_info2"
            }
        ]';

$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$cells = ['name' => 'C', 'age' => 'F', 'other_info' => 'J', 'my_info' => 'L'];
$array = json_decode($json, true);

$rowID = 17;
foreach($array as $rowArray) {
    foreach ($rowArray as $index => $columnValue) {
        $col = $cells[$index].$rowID;
        $phpExcelObject
          ->getActiveSheet()
          ->setCellValue((string)$col, $columnValue);
    }
    $rowID++;
}
© www.soinside.com 2019 - 2024. All rights reserved.