从对象数组创建PHPExcel

时间:2016-06-06 07:43:18

标签: php phpexcel

我有一个从数据库读取并创建Person对象的PersonMapper(PHP Slim Framework 3):

<?php
class PersonMapper extends Mapper {

    public function getPersons() {
        $stmt = $this->db->query("SELECT p.id, p.firstname, p.pastname FROM persons p");
        $results = [];
        while($row = $stmt->fetch()) {
            $results[] = new Person($row);
        }
        return $results;
    }
}

class Person implements ArrayAccess {
    protected $id;
    protected $firstname;
    protected $lastname;

    public function __construct(array $data) {
        // no id if we're creating
        if(isset($data['id'])) { $this->id = $data['id']; }
        $this->firstname= $data['firstname'];
        $this->lastname= $data['lastname'];
    }

    public function getId() { return $this->id; }
    public function getFirstname() { return $this->firstname; }
    public function getLastname() { return $this->lastname; }

    public function offsetExists($offset) {
        return array_key_exists($offset, $this->asArray());
    }

    public function offsetGet($offset) {
        return $this->offsetExists($offset) ? $this->asArray()[$offset]:NULL;
    }

    public function offsetSet($offset, $value) {
        $this->asArray()[$offset] = $value; 
    }

    public function offsetUnset($offset) {
        if ($this->offsetExists($offset)) {
            $_array = $this->asArray();
            unset($_array[$offset]);
        }
    }

    public function asArray() {
        return array(
            'id' => $this->id, 
            'firstname' => $this->firstname, 
            'kurzbezeichnung' => $this->lastname);
    }
}

我现在能够获得一系列人物对象:

$mapper = new PersonMapper($this->db);
$persons= $mapper->getPersons();

现在我想将人员列表放入excel文件中:

    $excelDoc = new PHPExcel();
    $excelDoc->setActiveSheetIndex(0);
    $excelDoc->getActiveSheet()->fromArray($persons, null, 'A1');

    $writer = PHPExcel_IOFactory::createWriter($excelDoc, 'Excel2007');
    $writer->save("persons.xlsx");

不幸的是,PHPExcel无法处理这种数据结构:

Catchable fatal error: Object of class Person could not be converted to
string in /path/to/src/vendor/phpoffice/phpexcel/Classes/
PHPExcel/Cell/DefaultValueBinder.php on line 65

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

请尝试:As per oficial documentation,首先需要使用对象编写器保存文件

如果这是你想要的,请告诉我

    <?php
date_default_timezone_set('America/Los_Angeles');

require_once('PHPExcel.php');

$sheet = array(
    array(
      'a1 data',
      'b1 data',
      'c1 data',
      'd1 data',
    )
  );

  $doc = new PHPExcel();
  $doc->setActiveSheetIndex(0);

  $doc->getActiveSheet()->fromArray($sheet, null, 'A1');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

  // Do your stuff here
  $writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');

$writer->save('php://output');
?>

答案 1 :(得分:0)

实施ArrayAccess后,您只需要遍历每个人,并将此人作为数组传递给fromArray。

我使用以下代码行进行了测试,但它确实有效:

将此部分$excelDoc->getActiveSheet()->fromArray($persons, null, 'A1');替换为此

$i = 1;
foreach ($persons as $person) {
    $excelDoc->getActiveSheet()->fromArray((array)$person, null, "A" . $i++);
}

这将在每个人的单元格A,B和C中粘贴ID,名字和kurzbezeichnung