1. PhpSpreadsheet是一个纯PHP类库,它提供了一组类,允许您从不同的电子表格文件格式(如Excel和LibreOffice Calc)读取和写入。用PHP读取Excel、CSV文件
  2. 还有一种类似的类库PHPExcel,但是PhpSpreadsheet代码质量和性能比PHPExcel高不少,完全可以替代PHPExcel(PHPExcel已不再维护)。

PhpSpreadsheet安装的环境要求:

  1. PHP version 7.4或者更高
  2. PHP extension:php_zip enabled,php_xml enabled,php_gd2 enabled

PhpSpreadsheet组件安装

  1. 使用composer执行命令安装依赖: composer require phpoffice/phpspreadsheet <版本号>
  2. 执行完命令后会在vendor目录下发现有了phpoffice目录,代表已经下载安装PhpSpreadsheet成功。

PhpSpreadsheet简单实例

<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
?>

官方帮助网站: https://phpspreadsheet.readthedocs.io/en/latest/

Phpword组件安装

  1. 使用composer执行命令安装依赖: composer require phpoffice/phpword <版本号>
  2. 执行完命令后会在vendor目录下发现有了phpoffice目录,代表已经下载安装Phpword成功。

PhpWord简单实例

<?php
require 'vendor/autoload.php';

// Creating the new document...
use PhpOffice\PhpWord\Settings;
$phpWord = new \PhpOffice\PhpWord\PhpWord();

/* Note: any element you append to a document must reside inside of a Section. */

// Adding an empty Section to the document...
$section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
    '"Learn from yesterday, live for today, hope for tomorrow. '
        . 'The important thing is not to stop questioning." '
        . '(Albert Einstein)'
);

/*
 * Note: it's possible to customize font style of the Text element you add in three ways:
 * - inline;
 * - using named font style (new font style object will be implicitly created);
 * - using explicitly created font style object.
 */

// Adding Text element with font customized inline...
$section->addText(
    '"Great achievement is usually born of great sacrifice, '
        . 'and is never the result of selfishness." '
        . '(Napoleon Hill)',
    array('name' => 'Tahoma', 'size' => 10)
);

// Adding Text element with font customized using named font style...
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
    $fontStyleName,
    array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
$section->addText(
    '"The greatest accomplishment is not in never falling, '
        . 'but in rising again after you fall." '
        . '(Vince Lombardi)',
    $fontStyleName
);

// Adding Text element with font customized using explicitly created font style object...
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('"Believe you can and you\'re halfway there." (Theodor Roosevelt)');
$myTextElement->setFontStyle($fontStyle);

// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');

// Saving the document as ODF file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('helloWorld.odt');

// Saving the document as HTML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('helloWorld.html');
?>

PHPword读取word文件代码样例

<?php
/**
 * Created by PhpStorm.
 * User: chengyanping
 * Date: 2021/5/19
 * Time: 13:14
 */
require_once './vendor/autoload.php';
ini_set('display_errors', true);
ini_set('max_execution_time', '0');
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
 
namespace common\services;
 
class WordService extends BaseService
{
 
    public static function importWord($info)
    {
        $word  = self::getWord($info['path']);
//      print_r($word);
        dd($word);
    }
 
    /**
     * 获取word文档内容
     * @param string $path
     * @return array
     */
    public static function getWord($path = '')
    {
        //加载word文档,使用phpword处理
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($path);
//   print_R($phpWord);exit();
        return self::getNodeContent($phpWord);
    }
 
    /**
     * 根据word主节点获取分节点内容
     * @param $word
     * @return array
     */
    public static function getNodeContent($word)
    {
        $return = [];
        //分解部分
        foreach ($word->getSections() as $section)
        {
            if ($section instanceof \PhpOffice\PhpWord\Element\Section) {
                //分解元素
                foreach ($section->getElements() as $element)
                {
                    //文本元素
                    if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
                        $text = '';
                        foreach ($element->getElements() as $ele) {
                            $text .= self::getTextNode($ele);
                        }
                        $return[] = $text;
                    }
                    //表格元素
                    else if ($element instanceof \PhpOffice\PhpWord\Element\Table) {
                        foreach ($element->getRows() as $ele)
                        {
                            $return[] = self::getTableNode($ele);
                        }
                    }
                }
            }
        }
        return $return;
    }
 
    /**
     * 获取文档节点内容
     * @param $node
     * @return string
     */
    public static function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .= $node->getText();
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            $return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }
 
    /**
     * 获取表格节点内容
     * @param $node
     * @return string
     */
    public static function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= self::getTableNode($ele);
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }
 
    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public static function pic2text($node)
    {
        //获取图片编码
        $imageData = $node->getImageStringData(true);
        //添加图片html显示标头
        $imageData = 'data:' . $node->getImageType() . ';base64,' . $imageData;
        $return = '<img src="'.$imageData.'">';
        return $return;
    }
    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public static function pic2file($node)
    {
        //图片地址(一般为word文档地址+在word中的锚点位置)
        $imageSrc  = 'images/' . md5($node->getSource()) . '.' . $node->getImageExtension();
        $imageData = $node->getImageStringData(true);
        //将图片保存在本地
        file_put_contents($imageSrc, base64_decode($imageData));
        return $imageSrc;
    }
 
    /**
     * 将word转化为html(转换存储html文件后展示)
     * @param $path
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    public static function word2html($path)
    {
        $phpWord = FileImportService::getOne($path);
        //转为html处理
        $xmlWriter  = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
        $path = pathinfo($path);
        $fileName = $path['dirname'] . '/' . $path['filename'] . '.html';
        $xmlWriter->save($fileName);
        $html = file_get_contents($fileName);
        echo $html;
        die;
 
    }
 
}

类似文章