PHPword导入,导出

目录

一、下载phpword

二、解析word文档导入

三、php生成word文档导出


一、下载phpword

composer require phpoffice/phpword

二、解析word文档导入

 注意:如果文档解析失败,请把文档中的图片重新上传下再试,有部分未知图片类型不支持解析

 require_once dirname(dirname(__FILE__)) . '/api/vendor/autoload.php';

    class WordService
    {
        public function importWord($info)
        {
            $word = self::getWord($info);
            //        print_r($word);
            return $word;
        }

        /**
         * 获取word文档内容
         * @param string $path
         * @return array
         */
        public static function getWord($path = '')
        {
            //加载word文档,使用phpword处理
            try {
                $phpWord = \PhpOffice\PhpWord\IOFactory::load($path);
                //        print_R($phpWord);exit();
                return self::getNodeContent($phpWord);
            } catch (Exception $phpWord) {
                //print_r($phpWord->getMessage());
                setcookie("alertHtml", "图片内容格式错误,请着重检查公式图片,建议图片重新上传");
                setcookie("alertIcon", "2");
                echo '<script>parent.location.reload();</script>';
                exit;
            }
        }

        /**
         * 根据word主节点获取分节点内容
         * @param $word
         * @return array
         */
        public static function getNodeContent($word)
        {
            $return_text = [];
            $return_html = [];
            //分解部分
            foreach ($word->getSections() as $section) {
                //$paragraphStyle = $section->getParagraphStyle();
                if ($section instanceof \PhpOffice\PhpWord\Element\Section) {
                    //分解元素
                    foreach ($section->getElements() as $element) {
                        //文本元素
                        if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
                            $item_text = '';
                            $item_html = '<p>';
                            foreach ($element->getElements() as $ele) {
                                $arr = self::getTextNode($ele);
                                $item_text .= $arr['text'];
                                $item_html .= $arr['html'];
                            }
                            $item_html .= '</p>';
                            $return_text[] = $item_text;
                            $return_html[] = $item_html;
                        } //表格元素
                        else if ($element instanceof \PhpOffice\PhpWord\Element\Table) {
                            /*$item_text = array();
                            $item_html = array();
                            foreach ($element->getRows() as $ele) {
                                $arr = self::getTableNode($ele);
                                $item_text[] = $arr['text'];
                                $item_html[] = $arr['html'];
                            }
                            $return_text[] = $item_text;
                            $return_html[] = $item_html;*/

                            $item_text = '表格';
                            $item_html = '<table width="100%" border="1" cellspacing="0" cellpadding="5">';
                            $item_htmlaaaa = array();
                            foreach ($element->getRows() as $ele) {
                                $arr = self::getTableNode($ele);
                                $item_text .= $arr['text'] ? implode(',', $arr['text']) : '';
//                            $item_html .= $arr['html'] ? implode(',', $arr['html']) : '';
                                $item_htmlaaaa[] = $arr['html'];
                            }
                            if (count($item_htmlaaaa) > 0) {
                                foreach ($item_htmlaaaa as $rstr) {
                                    $item_html .= '<tr>';
                                    foreach ($rstr as $rstd) {
                                        $item_html .= '<td>' . $rstd . '</td>';
                                    }
                                    $item_html .= '</tr>';
                                }
                            }

                            $item_html .= '</table>';
                            $return_text[] = $item_text;
                            $return_html[] = $item_html;
                        } //处理链接
                        else if ($element instanceof \PhpOffice\PhpWord\Element\Link) {
                            $item_text = $element->getText();
                            $item_html = '<a href="' . $element->getSource() . '">' . $item_text . '</a>';
                            $return_text[] = $item_text;
                            $return_html[] = $item_html;
                        } //保留文本元素
                        else if ($element instanceof \PhpOffice\PhpWord\Element\PreserveText) {
                            //当是预留文本的时候
                            $item_text = '';
                            $item_html = '<p>';
                            foreach ($element->getText() as $ele => $value) {
                                $item_text .= $value;
                                $item_html .= $value;
                            }
                            $item_html .= '</p>';
                            $return_text[] = $item_text;
                            $return_html[] = $item_html;
                        }
                    }
                }
            }
            return array('text' => $return_text, 'html' => $return_html);
        }

        /**
         * 获取文档节点内容
         * @param $node
         * @return array
         */
        public static function getTextNode($node)
        {
            $return_text = '';
            $return_html = '';
            //处理文本
            if ($node instanceof \PhpOffice\PhpWord\Element\Text) {
                $style = $node->getFontStyle();
                $fontFamily = $style->getName();
                $fontSize = $style->getSize();
                $fontColor = $style->getColor();
                $isBold = $style->isBold();
                $isItalic = $style->isItalic();                 //斜体
                $isStrikethrough = $style->isStrikethrough();   //删除线
                $isUnderline = $style->getUnderline();
                $styleString = '';
                $fontFamily && $styleString .= "font-family:{$fontFamily};";
                $fontSize && $styleString .= "font-size:{$fontSize}px;";
                $fontColor && $styleString .= "color:{$fontColor};";
                $isBold && $styleString .= "font-weight:bold;";
                $isItalic && $styleString .= "font-style:italic;";
                if ($isStrikethrough) {
                    $styleString .= "text-decoration:line-through;";
                } else if ($isUnderline != 'none') {
                    $styleString .= "text-decoration:underline;";
                }
                //echo '<pre>';
                //print_r($styleString);
                //exit;
                $html = $styleString ? "<span style='{$styleString}'>{$node->getText()}</span>" : $node->getText();
                if ($isUnderline == 'single') {
                    $html = "<u>{$html}</u>";
                }
                $return_text .= $node->getText();
                $return_html .= $html;
            } //处理图片
            else if ($node instanceof \PhpOffice\PhpWord\Element\Image) {
                $return_text .= self::pic2file($node);
                $return_html .= self::pic2file($node);
            } //处理文本元素
            else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
                foreach ($node->getElements() as $ele) {
                    $arr = self::getTextNode($ele);
                    $return_text .= $arr['text'];
                    $return_html .= $arr['html'];
                }
            } //处理保留文本
            else if ($node instanceof \PhpOffice\PhpWord\Element\PreserveText) {
                $data = $node->getText();
                $find = array('{', 'HYPERLINK', '}', ' ', '"', 'f', 'g');
                $replace = '';
                $resText = str_replace($find, $replace, $data);
                $return_text .= $resText[0];
                $return_html .= $resText[0];
            }
            //echo '<pre>';
            //print_r(array('text' => $return_text, 'html' => $return_html));
            //exit;
            return array('text' => $return_text, 'html' => $return_html);
        }

        /**
         * 获取表格节点内容
         * @param $node
         * @return array
         */
        public static function getTableNode($node)
        {
            $return_arr = [];
            $return_text = [];
            $return_html = [];
            //处理行
            if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
                foreach ($node->getCells() as $ele) {
                    //$return_arr[] = self::getTableNode($ele);
                    $arr = self::getTableNode($ele);
                    $return_text[] = $arr['text'];
                    $return_html[] = $arr['html'];
                }
            } //处理列
            else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
                foreach ($node->getElements() as $ele) {
                    $return_arr = self::getTextNode($ele);
                    $return_text = $return_arr['text'];
                    $return_html = $return_arr['html'];
                }
            }
            //return $return_arr;
            return array('text' => $return_text, 'html' => $return_html);
        }

        /**
         * 处理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_src = '/images/' . md5($node->getSource()) . '.' . $node->getImageExtension();
            $imageSrc = dirname(dirname(__FILE__)) . $imageSrc_src;
            $imageData = $node->getImageStringData(true);
            //将图片保存在本地
            file_put_contents($imageSrc, base64_decode($imageData));
            $return = '<img src="' . $imageSrc_src . '">';
            return $return;
            //return $imageSrc;
        }

        /**
         * 将word转化为html(转换存储html文件后展示)
         * @param $path
         * @throws \PhpOffice\PhpWord\Exception\Exception
         */
        public static function word2html($path)
        {
            //$phpWord = FileImportService::getOne($path);
            $phpWord = \PhpOffice\PhpWord\IOFactory::load($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;
        }

        public function deleteFile($filePath)
        {
            if (file_exists($filePath)) {
                $tt = unlink($filePath);
                return $tt;
            } else {
                return false;
            }
        }
    }

 
    $types_path = $_POST["types_path"];//word文件地址
    


    $save_path = dirname(dirname(__FILE__)) . $types_path;
    $WordService = new WordService();
    $res = $WordService->importWord($save_path);
    $html_arr = $res['html'];//文档接口返回的html数组
    $text_arr = $res['text'];//文档接口返回纯数字数组

    
echo '<pre>';
print_r($html_arr);
echo '<pre>';
print_r($text_arr);
exit();

三、php生成word文档导出

模板文档(demo.docx)

//检测目录是否存在
function uploadDirectory($uploadDir)
{
    // 如果目录不存在,则创建目录
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
}

require_once dirname(dirname(__FILE__)) . '/api/vendor/autoload.php';
//模板文件
$save_path = dirname(dirname(__FILE__)) . '/images/demo.docx';
//1.创建模板对象
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($save_path);

//2.插入数据
//插入文字
$templateProcessor->setValue('hao', '123123');
$templateProcessor->setValue('time', '2023年7月11日10:00--18:00');
$templateProcessor->setValue('name', '王某某');
$templateProcessor->setValue('sex', '男');
$templateProcessor->setValue('butime', '2023-12-30');
$templateProcessor->setValue('leixing', '特种作业人员');
$templateProcessor->setValue('gsname', '西藏某某');
$templateProcessor->setValue('kemu', '金属某某');
$templateProcessor->setValue('addr', '拉萨市某某考场');
$templateProcessor->setValue('sfleixing', '身份证');
$templateProcessor->setValue('sfhao', '11111111111111');

//插入图片,宽200像素,高300像素
$picParam = ['path' => dirname(dirname(__FILE__)) . '/image/20230720/baabe44df21da27830d7745a8f10c413.jpg', 'width' => 150, 'height' => 200];
$templateProcessor->setImageValue('picurl', $picParam);

$imageSrc = '/image/download/' . date("Ymd") . '/';
//检测目录,没有则创建
uploadDirectory(dirname(dirname(__FILE__)) . $imageSrc);
$url = dirname(dirname(__FILE__)) . $imageSrc . build_order_no() . '.docx';
try {
    //图片保存到服务器
    $templateProcessor->saveAs($url);
} catch (Exception $e) {
    echo '保存出错,请联系管理员';
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值