laravel框架实现phpExcel导入导出

本文介绍如何在Laravel框架中利用PHPExcel库进行Excel数据的导入和导出操作。首先需配置Composer并引入PHPExcel类,然后通过具体代码示例展示了数据导出过程,包括设置文件属性、字段名及内容填充;同时也分享了数据导入的方法,涉及文件类型判断、读取及插入数据库等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

laravel框架实现phpExcel导入导出,首先必须在laravel引入第三方类

1、在app目录下创建一个新的文件夹,命名libs(可自定义)

2、(可选)考虑到后面可能会引用很多库,so,在libs下再创建一个phpExcel文件夹,把phpExcel类放入此文件夹下。

3、找到根目录下的composer.json文件

4、找到composer.json中定义的(看我备注)

           "autoload": {  

                 "classmap": [  

                      "database",  

                     "app/libs/phpExcel"  //加入phpExcel类的路径 

                  ],  

              "psr-4": {  

                    "App\\": "app/"  

               }

        },

5、安装composer,windows下可以在百度上下载

6、运行命令行进入项目根目录,执行“composer dumpautoload”

7、在控制器中use PHPExcel

8、在方法中实例化phpExccel对象,打印该对象看phpExcel类是否引入成功。

     $objPHPExcel = new PHPExcel();

     print_r($objPHPExcel);

==========以上是引入phpExcel类步骤(其它第三方类与此类似)============

  1. <span style="font-size:18px;">以下开始excel导入导出</span>  
<span style="font-size:18px;">以下开始excel导入导出</span>


//导出     控制器中use PHPExcel;  use IOFactory;

  1. publicfunction phpexcel()  
  2. {  
  3.   
  4.        //$objPHPExcel = new PHPExcel();  
  5.   
  6.        //print_r($objPHPExcel);  
  7.   
  8.         $query =DB::table('goods')->get();  
  9.   
  10.         //$query =$this ->db->query($sql);  
  11.   
  12.        //print_r($query);  
  13.   
  14.         if(!$query)return false;  
  15.   
  16.         //StartingthePHPExcellibrary  
  17.   
  18.         //加载PHPExcel类  
  19.   
  20.        //$this->load->library('PHPExcel');  
  21.   
  22.         //$this->load ->library('PHPExcel/IOFactory');  
  23.   
  24.         $objPHPExcelnew PHPExcel();  
  25.   
  26.         include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');  
  27.   
  28.         $objPHPExcel->getProperties()-> setTitle("export") ->setDescription("none");  
  29.   
  30.         $objPHPExcel-> setActiveSheetIndex(0);  
  31.   
  32.         //Fieldnamesinthefirstrow  
  33.   
  34.         $fields = DB::select("select COLUMN_NAME from information_schema.COLUMNS where  
  35.   
  36.            table_name = 'goods';");  
  37.   
  38.        //print_r($fields);die;  
  39.   
  40.         $col = 0;  
  41.   
  42.        foreach($fields as $field){  
  43.   
  44.             $field =$field['COLUMN_NAME'];  
  45.   
  46.             $objPHPExcel-> getActiveSheet() -> setCellValueByColumnAndRow($col, 1,$field);  
  47.   
  48.             $col++;  
  49.   
  50.         }  
  51.   
  52.        // die;  
  53.        //Fetchingthetabledata  
  54.   
  55.        $row = 2;  
  56.   
  57.         foreach($query as $data)  
  58.         {  
  59.   
  60.              $col =0;  
  61.   
  62.              foreach($fields $field)  
  63.   
  64.              {  
  65.   
  66.                  //print_r($data);  
  67.   
  68.                  $field =$field['COLUMN_NAME'];  
  69.   
  70.                  $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col,$row,!empty($data["$field"])?$data["$field"]:'');  
  71.   
  72.                  $col++;  
  73.   
  74.              }  
  75.   
  76.             $row++;  
  77.   
  78.         }  
  79.   
  80.         //die;  
  81.   
  82.         $objPHPExcel-> setActiveSheetIndex(0);  
  83.   
  84.         $objWriter =IOFactory :: createWriter($objPHPExcel'Excel5');  
  85.   
  86.         //Sendingheaderstoforcetheusertodownloadthefile  
  87.   
  88.         header('Content-Type:application/vnd.ms-excel');  
  89.   
  90.        //header('Content-Disposition:attachment;filename="Products_' .date('dMy') . '.xls"');  
  91.   
  92.         header('Content-Disposition:attachment;filename="Brand_' .date('Y-m-d') . '.xls"');  
  93.   
  94.         header('Cache-Control:max-age=0');  
  95.   
  96.         $objWriter-> save('php://output');  
  97.   
  98.     }  
publicfunction phpexcel()
{

       //$objPHPExcel = new PHPExcel();

       //print_r($objPHPExcel);

        $query =DB::table('goods')->get();

        //$query =$this ->db->query($sql);

       //print_r($query);

        if(!$query)return false;

        //StartingthePHPExcellibrary

        //加载PHPExcel类

       //$this->load->library('PHPExcel');

        //$this->load ->library('PHPExcel/IOFactory');

        $objPHPExcel= new PHPExcel();

        include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');

        $objPHPExcel->getProperties()-> setTitle("export") ->setDescription("none");

        $objPHPExcel-> setActiveSheetIndex(0);

        //Fieldnamesinthefirstrow

        $fields = DB::select("select COLUMN_NAME from information_schema.COLUMNS where

           table_name = 'goods';");

       //print_r($fields);die;

        $col = 0;

       foreach($fields as $field){

            $field =$field['COLUMN_NAME'];

            $objPHPExcel-> getActiveSheet() -> setCellValueByColumnAndRow($col, 1,$field);

            $col++;

        }

       // die;
       //Fetchingthetabledata

       $row = 2;

        foreach($query as $data)
        {

             $col =0;

             foreach($fields $field)

             {

                 //print_r($data);

                 $field =$field['COLUMN_NAME'];

                 $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col,$row,!empty($data["$field"])?$data["$field"]:'');

                 $col++;

             }

            $row++;

        }

        //die;

        $objPHPExcel-> setActiveSheetIndex(0);

        $objWriter =IOFactory :: createWriter($objPHPExcel, 'Excel5');

        //Sendingheaderstoforcetheusertodownloadthefile

        header('Content-Type:application/vnd.ms-excel');

       //header('Content-Disposition:attachment;filename="Products_' .date('dMy') . '.xls"');

        header('Content-Disposition:attachment;filename="Brand_' .date('Y-m-d') . '.xls"');

        header('Cache-Control:max-age=0');

        $objWriter-> save('php://output');

    }


 

//导入     控制器中use IOFactory;   use PHPExcel_Cell;

  1. public functionru(Request $request){  
  2.        $tmp_file =$_FILES ['file_stu'] ['tmp_name'];  
  3.   
  4.        $file_types =explode ( "."$_FILES ['file_stu'] ['name'] );  
  5.   
  6.        $file_type =$file_types [count ( $file_types ) - 1];  
  7.   
  8.        /*判别是不是.xls文件,判别是不是excel文件*/  
  9.   
  10.        if (strtolower$file_type ) != "xls"){  
  11.   
  12.           $this->error ( '不是Excel文件,重新上传' );  
  13.   
  14.        }  
  15.   
  16.        $savePath ="./excel/";  
  17.   
  18.        /*以时间来命名上传的文件*/  
  19.   
  20.        $str =date('Ymdhis');  
  21.   
  22.        $file_name =$str . "." . $file_type;  
  23.   
  24.        //echo$file_name;die;  
  25.   
  26.        $request->file('file_stu')->move($savePath$file_name);  
  27.   
  28.        /*是否上传成功*/  
  29.   
  30.        /*if(!copy($tmp_file,$savePath.$file_name)){ 
  31.  
  32.           $this->error ( '上传失败' ); 
  33.  
  34.        }*/  
  35.   
  36.        //要获得新的文件路径+名字  
  37.   
  38.        $fullpath =$savePath.$file_name;  
  39.   
  40.        //echo$fullpath;die;  
  41.   
  42.        $re =$this->read($fullpath,'utf-8');  
  43.   
  44.        //print_r($re);die;  
  45.   
  46.        for($i=1;$i<count($re);$i++){  
  47.   
  48.           //print_r($re);  
  49.   
  50.           //echo$re[$i][1];  
  51.   
  52.           $adds =DB::table('goods')->insert(['gname' => $re[$i][1], 'gprice' =>$re[$i][2]]);  
  53.   
  54.        }  
  55.   
  56.        //die;  
  57.   
  58.        if($adds){  
  59.   
  60.             echo"<script>alert('导入成功');location.href='daoru'</script>";  
  61.   
  62.         }else{  
  63.   
  64.             echo"<script>alert('导入失败');location.href='daoru'</script>";  
  65.   
  66.         }  
  67.   
  68.    
  69.   
  70.     }  
  71.   
  72. public function read($filename,$encode='utf-8')  
  73. {  
  74.   
  75.         include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');  
  76.   
  77.         //$this->load ->library('PHPExcel/IOFactory');  
  78.   
  79.         $objReader =IOFactory::createReader('Excel5');  
  80.   
  81.         $objReader->setReadDataOnly(true);  
  82.   
  83.         $objPHPExcel$objReader->load($filename);  
  84.   
  85.         $objWorksheet$objPHPExcel->getActiveSheet();  
  86.   
  87.         $highestRow =$objWorksheet->getHighestRow();  
  88.   
  89.         //echo$highestRow;die;  
  90.   
  91.         $highestColumn = $objWorksheet->getHighestColumn();  
  92.   
  93.         //echo$highestColumn;die;  
  94.   
  95.         $highestColumnIndex =PHPExcel_Cell::columnIndexFromString($highestColumn);  
  96.   
  97.         $excelData =array();  
  98.   
  99.         for($row = 1;$row <= $highestRow$row++) {  
  100.   
  101.             for ($col= 0; $col < $highestColumnIndex$col++) {  
  102.   
  103.                    $excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();  
  104.   
  105.              }  
  106.   
  107.         }  
  108.   
  109.         return$excelData;  
  110.   
  111. }  
public functionru(Request $request){
       $tmp_file =$_FILES ['file_stu'] ['tmp_name'];

       $file_types =explode ( ".", $_FILES ['file_stu'] ['name'] );

       $file_type =$file_types [count ( $file_types ) - 1];

       /*判别是不是.xls文件,判别是不是excel文件*/

       if (strtolower( $file_type ) != "xls"){

          $this->error ( '不是Excel文件,重新上传' );

       }

       $savePath ="./excel/";

       /*以时间来命名上传的文件*/

       $str =date('Ymdhis');

       $file_name =$str . "." . $file_type;

       //echo$file_name;die;

       $request->file('file_stu')->move($savePath, $file_name);

       /*是否上传成功*/

       /*if(!copy($tmp_file,$savePath.$file_name)){

          $this->error ( '上传失败' );

       }*/

       //要获得新的文件路径+名字

       $fullpath =$savePath.$file_name;

       //echo$fullpath;die;

       $re =$this->read($fullpath,'utf-8');

       //print_r($re);die;

       for($i=1;$i<count($re);$i++){

          //print_r($re);

          //echo$re[$i][1];

          $adds =DB::table('goods')->insert(['gname' => $re[$i][1], 'gprice' =>$re[$i][2]]);

       }

       //die;

       if($adds){

            echo"<script>alert('导入成功');location.href='daoru'</script>";

        }else{

            echo"<script>alert('导入失败');location.href='daoru'</script>";

        }

 

    }

public function read($filename,$encode='utf-8')
{

        include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');

        //$this->load ->library('PHPExcel/IOFactory');

        $objReader =IOFactory::createReader('Excel5');

        $objReader->setReadDataOnly(true);

        $objPHPExcel= $objReader->load($filename);

        $objWorksheet= $objPHPExcel->getActiveSheet();

        $highestRow =$objWorksheet->getHighestRow();

        //echo$highestRow;die;

        $highestColumn = $objWorksheet->getHighestColumn();

        //echo$highestColumn;die;

        $highestColumnIndex =PHPExcel_Cell::columnIndexFromString($highestColumn);

        $excelData =array();

        for($row = 1;$row <= $highestRow; $row++) {

            for ($col= 0; $col < $highestColumnIndex; $col++) {

                   $excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();

             }

        }

        return$excelData;

}

phpExcel导入导出终于完成了,赶快尝试一下吧!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值