如何通过 phpword 库读取 table 单元格内容

How to read table cell content via phpword library

这是我目前拥有的代码

$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
$sections = $phpWord->getSections();
foreach ($sections as $s) {
    $els = $s->getElements();
    foreach ($els as $e) {
        switch (get_class($element)) {
            case 'PhpOffice\PhpWord\Element\TextRun':
                $this->logger->debug("TextRun");
                $this->getTextFromTextRun($element);
                break;

            case 'PhpOffice\PhpWord\Element\Table':
                $this->logger->debug("Table");
                $this->iterateOverRows($element);
                break;
        }
    }
}


private function getTextFromTextRun($element) {
    for ($index = 0; $index < $element->countElements(); $index++) {
        $textRunElement = $element->getElement($index);
        $text = $textRunElement->getText();
        if (strlen($text) > 0) {
            $this->logger->debug("TextRun Text: " . $text);
        }
    }
}

private function iterateOverRows($table) {
    $rows = $table->getRows();
    foreach ($rows as $row) {
        foreach ($row->getCells() as $cell) {
            // What to do here???
        }
    }
}

我不知道如何从单元格中获取内容?

这些是 cell-object 中可用的 getter 方法:

在这里解决了这个问题:

private function iterateOverRows($table) {
    $rows = $table->getRows();
    foreach ($rows as $row) {
        foreach ($row->getCells() as $cell) {
            $els = $cell->getElements();
            foreach ($els as $e) {
                $this->switchElements($e);
            }
        }
    }
}


private function switchElements($element) {
    switch (get_class($element)) {
        case 'PhpOffice\PhpWord\Element\TextRun':
            $this->getTextFromTextRun($element);
            break;

        case 'PhpOffice\PhpWord\Element\Table':
            $this->iterateOverRows($element);
            break;

        default:
            break;
    }
}


private function getTextFromTextRun($element) {
    for ($index = 0; $index < $element->countElements(); $index++) {
        $textRunElement = $element->getElement($index);

        switch (get_class($textRunElement)) {
            case 'PhpOffice\PhpWord\Element\Text':
            case 'PhpOffice\PhpWord\Element\TextRun':
                $text = $textRunElement->getText();
                if (strlen($text) > 0) {
                    $this->logger->debug("Text: " . $text);
                    $this->getFont($textRunElement);
                }
                break;

            case 'PhpOffice\PhpWord\Element\TextBreak':
                break;

            default:
                break;
        }
    }
}