PHPExcel 上传下载的示例代码

1:首先用composer require phpoffice/phpexcel

2: 引入相关的类:

use PHPExcel;
use PHPExcel_Cell;
use PHPExcel_Writer_Excel5;

3:下载具体代码


    public function exportExcel()
    {
        $dataArr = Admin::all();
        //创建PHPExcel对象
        $obj = new PHPExcel();
        //创建excel写入对象
        $writer = new PHPExcel_Writer_Excel5($obj);
        //得到当前工作表对象
        $curSheet = $obj->getActiveSheet(0);
        foreach ($dataArr as $row => $admObj) { //row 是行,注意从0开始,外循环是行,
            $col = 0;
            foreach ($admObj->getData() as $field => $value) {
              //  echo $row ."<=>".$col."  , ".$field."=>".$value.'
'; // die(); if ($row == 0) { // $num 控制的是行,$col控制的是列 //第一行 $cellName = PHPExcel_Cell::stringFromColumnIndex($col) . ($row + 1);//取单元格 $curSheet->setCellValue($cellName, $field);//给单元格赋值 //第二行 $cellName = PHPExcel_Cell::stringFromColumnIndex($col) . ($row + 2); $curSheet->setCellValue($cellName, $value); } else { $cellName = PHPExcel_Cell::stringFromColumnIndex($col) . ($row + 2); $curSheet->setCellValue($cellName, $value); } $col++; } } $fileName = date('YmdHis', time()); header('Content-Type: application/vnd.ms-execl'); header('Content-Disposition: attachment;filename="' . $fileName . '.xls"'); header('Cache-Control: max-age=0'); $writer->save('php://output'); }

4:上传具体代码:

    /**
     * EXCEL 文件上传并导入数据库
     * @throws \PHPExcel_Exception
     */
    public function doUpload()
    {
        $file = request()->file('excel');//接收上传的文件
        // 定义文件上传的目录(文件夹)
        $uploadDir = '/home/project/kona/think51/public/upload/excel/';
        //将文件上传到目标文件夹
       $info = $file->move($uploadDir);
        if ($info) {//文件上传成功
            // 获取上传文件的路径(包括文件夹和文件名)
           $fileName = $uploadDir.$info->getSaveName();
            //将文件放入PHPEXcel的读取器中
            $phpExcelObj = \PHPExcel_IOFactory::load($fileName);
            //读取PHPEXcel的sheet[0]的数据,并转换为数组
            $sheet = $phpExcelObj->getSheet(0)->toArray();
            //移出数组的第一个元素(在此处数组),并赋值给fields,sheet中不在包含表头行了
            $fields = array_shift($sheet);
            foreach ($sheet as $row => $ary) {//遍历
                    //将表头和内容合并成一个数组
                    $newarr = array_combine($fields, $ary);
                    unset($newarr['id']);//ID不能插入,删除key为ID的元素
                    //$newarr['pwd'] = md5($newarr['pwd']);
                    $admin = new Admin();
                    $res=$admin->save($newarr);
                    if(empty($res)) {
                        $this->success("数据上传失败", "index");
                    }
            }
            $this->success("上传成功并插入数据库", "index");
        } else {
            $this->error($file->getError(), "index");
       }
    }

 

你可能感兴趣的:(新手必备,php7)