将对象数组添加到 PHPExcel 模板
Add array of objects to PHPExcel template
我目前正在从我的数据库中提取一组对象,目的是每个对象代表 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 sheet 中的行从 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++;
}
}
任何人都可以给我一些指导吗?非常感谢!
试试这个:
$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++;
}
我目前正在从我的数据库中提取一组对象,目的是每个对象代表 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 sheet 中的行从 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++;
}
}
任何人都可以给我一些指导吗?非常感谢!
试试这个:
$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++;
}