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 '保存出错,请联系管理员';
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是 PHP 代码示例,用于从 MySQL 数据库导出数据到 Excel 文件: ``` <?php // 连接数据库 $conn = mysqli_connect("hostname", "username", "password", "database_name"); // 检查连接是否成功 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } // 查询数据库并导出到 Excel 文件 $sql = "SELECT * FROM table_name"; $result = mysqli_query($conn, $sql); // 创建 PHPExcel 对象 $objPHPExcel = new PHPExcel(); // 设置工作表 $objPHPExcel->setActiveSheetIndex(0); $sheet = $objPHPExcel->getActiveSheet(); // 设置标题行 $sheet->setCellValue("A1", "列1"); $sheet->setCellValue("B1", "列2"); ... // 循环读取数据库中的数据 $row = 2; // 从第2行开始 while ($row_data = mysqli_fetch_assoc($result)) { $sheet->setCellValue("A".$row, $row_data["column1"]); $sheet->setCellValue("B".$row, $row_data["column2"]); ... $row++; } // 设置保存路径 $file_name = "导出文件名.xlsx"; $save_path = "导出文件路径/".$file_name; // 保存 Excel 文件 $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); $objWriter->save($save_path); // 关闭数据库连接 mysqli_close($conn); // 输出下载链接 echo "文件导出,请点击 <a href='".$save_path."'>下载</a>"; ``` 以下是 PHP 代码示例,用于从 Excel 文件导入数据到 MySQL 数据库: ``` <?php // 连接数据库 $conn = mysqli_connect("hostname", "username", " ### 回答2: MySQL导入导出Excel是将MySQL数据库中的数据导出到Excel表格或将Excel表格中的数据导入到MySQL数据库中。 导出Excel使用的是PHPExcel库,首先需要安装这个库,并在代码中引入相应的类文件。然后连接MySQL数据库,编写SQL查询语句以获取所需数据。接着创建一个Excel对象,设置表头和数据,将查询结果逐行写入到Excel中。最后将Excel保存为文件并提供下载链接。 以下是一个简单的MySQL导出Excel的PHP代码示例: <?php require_once 'PHPExcel/PHPExcel.php'; // 连接MySQL数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 查询数据 $sql = "SELECT * FROM table"; $result = $conn->query($sql); // 创建Excel对象 $objPHPExcel = new PHPExcel(); $objPHPExcel->getActiveSheet()->setTitle('Sheet1'); // 设置表头 $objPHPExcel->getActiveSheet()->setCellValue('A1', '列1'); $objPHPExcel->getActiveSheet()->setCellValue('B1', '列2'); $objPHPExcel->getActiveSheet()->setCellValue('C1', '列3'); // 设置数据 $row = 2; while ($row_data = $result->fetch_assoc()) { $objPHPExcel->getActiveSheet()->setCellValue('A' . $row, $row_data['column1']); $objPHPExcel->getActiveSheet()->setCellValue('B' . $row, $row_data['column2']); $objPHPExcel->getActiveSheet()->setCellValue('C' . $row, $row_data['column3']); $row++; } // 保存Excel文件 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('output.xlsx'); // 提供下载链接 echo '<a href="output.xlsx">Download Excel</a>'; // 关闭数据库连接 $conn->close(); ?> 导入Excel同样使用PHPExcel库,首先需要将Excel文件上传到服务器上,并在代码中获取上传文件的路径。然后连接MySQL数据库,编写插入语句以将数据插入到数据库中。接着使用PHPExcel的读取功能,读取Excel文件的内容并逐行插入到数据库中。 以下是一个简单的MySQL导入Excel的PHP代码示例: <?php require_once 'PHPExcel/PHPExcel.php'; // 连接MySQL数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 获取上传文件路径 $file_path = 'path/to/uploaded/file.xlsx'; // 读取Excel文件 $objReader = PHPExcel_IOFactory::createReader('Excel2007'); $objPHPExcel = $objReader->load($file_path); $sheet = $objPHPExcel->getSheet(0); // 获取行数 $highestRow = $sheet->getHighestRow(); // 读取数据并插入数据库 for ($row = 2; $row <= $highestRow; $row++) { $column1 = $sheet->getCell('A' . $row)->getValue(); $column2 = $sheet->getCell('B' . $row)->getValue(); $column3 = $sheet->getCell('C' . $row)->getValue(); $sql = "INSERT INTO table (column1, column2, column3) VALUES ('$column1', '$column2', '$column3')"; if ($conn->query($sql) !== TRUE) { echo "Error: " . $sql . "<br>" . $conn->error; } } // 关闭数据库连接 $conn->close(); ?> 以上是一个基本的MySQL导入导出Excel的PHP代码示例,根据实际需求可以进行相应的修改和扩展。 ### 回答3: MySQL导入导出Excel可以使用PHP代码来实现。以下是一个示例代码: 导出Excel文件: ``` <?php // 导出Excel文件 require_once 'PHPExcel.php'; // 创建一个新的PHPExcel对象 $objPHPExcel = new PHPExcel(); // 设置Excel文件的属性 $objPHPExcel->getProperties()->setCreator("Your Name") ->setLastModifiedBy("Your Name") ->setTitle("Excel Document") ->setSubject("Excel Document") ->setDescription("Test document for Excel") ->setKeywords("excel php") ->setCategory("Test"); // 添加数据到Excel文件中 $objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello') ->setCellValue('B1', 'World!'); // 导出Excel文件 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="example.xlsx"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); exit; ?> ``` 导入Excel文件: ``` <?php // 导入Excel文件 require_once 'PHPExcel.php'; // 获取上传的Excel文件 $file = $_FILES['file']['tmp_name']; // 读取Excel文件内容 $objPHPExcel = PHPExcel_IOFactory::load($file); // 获取第一个工作表 $sheet = $objPHPExcel->getSheet(0); // 获取行数和列数 $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); // 循环读取数据 for ($row = 1; $row <= $highestRow; $row++) { // 读取每一列的数据 for ($col = 'A'; $col <= $highestColumn; $col++) { $data = $sheet->getCell($col.$row)->getValue(); // 处理数据 } } // 处理完数据之后可以进行其他操作 ?> ``` 以上是一个简单示例的MySQL导入导出Excel的PHP代码。你可以根据自己的需求修改代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值