php/thinkphp使用PHPExcel解析表格数据,生成表格案例

我使用的是thinkphp框架

遇到个一场景,发货员发货之后需要一个一个给用户发通知短信,效率太低,所以我就想到了模板短信,

降到效率问题,我是这样设计的,他把Excel导入,我通过phpExcel进行解析,匹配到姓名,电话,和订单号,订单类型

然后向用户发送通知短信,根据订单类型发送不同的订单查询地址和通知信息

------------------------------------------------------------------------------------------------------------------------------------------

这篇主要记录下我使用PHPExcel的过程

这篇不是远创,是看了好多大神的帖子后整理的,甚至说复制的代码,但是具体的原文我没有做记录,就不一点一点贴出来了

写此文仅供自己记录学习之用

----------------------------------------------------------------------------------------------------------------------------------------

1:下载PHPExcel

可以从官网下载,我也把文档上传了http://download.csdn.net/detail/fei003/9851672

2 把PHPExcel放入项目中

把PHPExcel解压后的文件放入Thinkphp/Library/Vendor中

3.把操作方法封装成函数(或者类库),方便自己使用

excel.php 函数

<?php
/**
 * Created by PhpStorm.
 * User: 飞
 * Date: 2017/6/13
 * Time: 10:20
 * 导入excel文件,对表格进行解析
 */
function importExecl($file,$filetype){
    if(!file_exists($file)){
        return array("error"=>0,'message'=>'file not found!');
    }
    // 判断文档类型,使用相应的方法,可以解析多种文件,这只是判断两个,其余的自己判断
    if($filetype == 'xlsx'){
        $filetype = 'Excel2007';
    }elseif($filetype == 'xls'){
        $filetype = 'Excel5';
    }
    // 引入扩展
    Vendor("PHPExcel.PHPExcel.IOFactory");
    $objReader = \PHPExcel_IOFactory::createReader($filetype);

    try{
        $PHPReader = $objReader->load($file);
    }catch(Exception $e){}
    if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!');
    // 获得所有的sheets表格
    $allWorksheets = $PHPReader->getAllSheets();
    $i = 0;
    //对sheet表格遍历分析
    foreach($allWorksheets as $objWorksheet){
        // 获得sheet表格的标题
        $sheetname=$objWorksheet->getTitle();
        // 获得总行数
        $allRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        // 获得总列数
        $allColumn = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $array[$i]["Title"] = $sheetname;
        $array[$i]["Cols"] = $allColumn;
        $array[$i]["Rows"] = $allRow;
        $arr = array();
        // 对合并的单元格进行分析
        $isMergeCell = array();
        foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells
            foreach (\PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
                $isMergeCell[$cellReference] = true;
            }
        }
        for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){
            $row = array();
            for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){;
                $cell =$objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
                $afCol = \PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);
                $bfCol = \PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);
                $col = \PHPExcel_Cell::stringFromColumnIndex($currentColumn);
                $address = $col.$currentRow;
                $value = $objWorksheet->getCell($address)->getValue();
                if(substr($value,0,1)=='='){
                    return array("error"=>0,'message'=>'can not use the formula!');
                    exit;
                }
                if($cell->getDataType()==\PHPExcel_Cell_DataType::TYPE_NUMERIC){
                    // $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();
                    // $formatcode=$cellstyleformat->getFormatCode();
                    if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $formatcode)) {
                        $value=gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($value));
                    }else{
                        $value=\PHPExcel_Style_NumberFormat::toFormattedString($value,$formatcode);
                    }
                }
                if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){
                    $temp = $value;
                }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){
                    $value=$arr[$currentRow-1][$currentColumn];
                }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){
                    $value=$temp;
                }
                $row[$currentColumn] = $value;
            }
            $arr[$currentRow] = $row;
        }
        $array[$i]["Content"] = $arr;
        $i++;
    }
    // spl_autoload_register('Think');//must, resolve ThinkPHP and PHPExcel conflicts
    unset($objWorksheet);
    unset($PHPReader);
    unset($PHPExcel);
    unlink($file);
    return array("error"=>1,"data"=>$array);
}

注意:实例化时命名空间要加\

使用的时候就简单了,下面是使用代码

<?php
namespace PhpExcel\Controller;
use Think\Controller;

/**
 * Created by PhpStorm.
 * User: 飞
 * Date: 2017/6/7
 * Time: 11:26
 */
class IndexController extends Controller
{
    public function index()
    {
        $this->display();
    }

    public function importExcel()
    {
        // 表单提交文件过来
        // 获得文件路径
        $file = $_FILES[excel][tmp_name];
        if(!file_exists($file)){
            echo '文件不存在';
            exit;
        }
        //
        $fileMessage = explode('.',$_FILES[excel][name]);
        // $filename = $fileMessage[0];
        // 获得文件扩展名
        $filetype = $fileMessage[1];
        //使用函数,获得excel数据
        $re = importExecl($file,$filetype);
        $content = $re['data'][0]['Content'];
        // P助手函数,自己扩展
        P($content);exit; /*逻辑代码*/
    }
}

然后在页面中打印如下

从页面上来看,数据解析的很不错

当然,拿到数据后,是不是想干什么就干什么呢。。。嘿嘿

---------------------------------------------------------------------------------------------------

另外一种场景就是把自己的数据生成excel表格

代码如下

public function outPortExcel()
{
    // 引入文件
    Vendor("PHPExcel.PHPExcel");
    vendor('PHPExcel/PHPExcel/Writer/Excel2007.php');
    $phpExcel = new \PHPExcel();
    $phpExcel->getProperties()->setTitle("Office 2007 XLSX Test Document title");
    $phpExcel->getProperties()->setSubject("Office 2007 XLSX Test Document subject");
    //单独添加数据
    $phpExcel->setActiveSheetIndex(0);
    $phpExcel->getActiveSheet()->setCellValue('A1', '姓名');//可以指定位置
    $phpExcel->getActiveSheet()->setCellValue('B1', '年龄');
    $phpExcel->getActiveSheet()->setCellValue('C1', '性别');
    $phpExcel->getActiveSheet()->setCellValue('D1', '家庭');
    //循环添加数据(根据自己的逻辑)
    for($i = 2;$i<200;$i++) {
        $phpExcel->getActiveSheet()->setCellValue('A' . $i, '张鹏飞'.$i);
        $phpExcel->getActiveSheet()->setCellValue('B' . $i, rand(25,28));
        $phpExcel->getActiveSheet()->setCellValue('C' . $i, rand(0,1));
        $phpExcel->getActiveSheet()->setCellValue('D' . $i, 'yes');
    }
    $objWriter = new \PHPExcel_Writer_Excel2007($phpExcel);
    // 文件名
    $filename = './a.xlsx';
    // 存储文件
    $objWriter->save($filename);

    // 下载文件
    // 强制下载函数 代码请转至 http://blog.csdn.net/fei003/article/details/54614097
    download('./a.xlsx');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

竖子敢尔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值