zoukankan      html  css  js  c++  java
  • Laravel 上使用 phpexcel的两种方式


    原创 2017年06月24日 20:24:31

    文章采集与网上

    方式1。使用原生的phpexcel ,

    http://blog.csdn.net/CSwfe/article/details/52748046?locationNum=1



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


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


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


    4、找到composer.json中定义的(看我备注)
    //加入phpExcel类的路径


    [html] view plain copy
    1.    "autoload": {    
    2.   
    3.   
    4.          "classmap": [    
    5.   
    6.   
    7.               "database",    
    8.   
    9.   
    10.                "app/libs/phpExcel"    
    11.   
    12.   
    13.           ],    
    14.   
    15.   
    16.       "psr-4": {    
    17.   
    18.   
    19.             "App\": "app/"    
    20.   
    21.   
    22.        }  
    23.   
    24.   
    25. },  



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


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


    7、在控制器中use PHPExcel


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


         $objPHPExcel = new PHPExcel();


         print_r($objPHPExcel);


    ==========以上是引入phpExcel类步骤(其它第三方类与此类似)============
     
        <span style="font-size:18px;">以下开始excel导入导出</span>  




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


    [php] view plain copy
    1. public function 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.         //Starting the PHPExcel library    
    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.     }    
    99.   
    100.   
    101.   
    102.   
    103.   
    104.   
    105.   
    106.   
    107.   
    108.      控制器中use IOFactory;   use PHPExcel_Cell;  
    109.   
    110.   
    111.   
    112. public function ru(Request $request){    
    113.        $tmp_file =$_FILES ['file_stu'] ['tmp_name'];    
    114.     
    115.        $file_types =explode ( "."$_FILES ['file_stu'] ['name'] );    
    116.     
    117.        $file_type =$file_types [count ( $file_types ) - 1];    
    118.     
    119.        /*判别是不是.xls文件,判别是不是excel文件*/    
    120.     
    121.        if (strtolower$file_type ) != "xls"){    
    122.     
    123.           $this->error ( '不是Excel文件,重新上传' );    
    124.     
    125.        }    
    126.     
    127.        $savePath ="./excel/";    
    128.     
    129.        /*以时间来命名上传的文件*/    
    130.     
    131.        $str =date('Ymdhis');    
    132.     
    133.        $file_name =$str . "." . $file_type;    
    134.     
    135.        //echo$file_name;die;    
    136.     
    137.        $request->file('file_stu')->move($savePath$file_name);    
    138.     
    139.        /*是否上传成功*/    
    140.     
    141.        /*if(!copy($tmp_file,$savePath.$file_name)){  
    142.   
    143.           $this->error ( '上传失败' );  
    144.   
    145.        }*/    
    146.     
    147.        //要获得新的文件路径+名字    
    148.     
    149.        $fullpath =$savePath.$file_name;    
    150.     
    151.        //echo$fullpath;die;    
    152.     
    153.        $re =$this->read($fullpath,'utf-8');    
    154.     
    155.        //print_r($re);die;    
    156.     
    157.        for($i=1;$i<count($re);$i++){    
    158.     
    159.           //print_r($re);    
    160.     
    161.           //echo$re[$i][1];    
    162.     
    163.           $adds =DB::table('goods')->insert(['gname' => $re[$i][1], 'gprice' =>$re[$i][2]]);    
    164.     
    165.        }    
    166.     
    167.        //die;    
    168.     
    169.        if($adds){    
    170.     
    171.             echo"<script>alert('导入成功');location.href='daoru'</script>";    
    172.     
    173.         }else{    
    174.     
    175.             echo"<script>alert('导入失败');location.href='daoru'</script>";    
    176.     
    177.         }    
    178.     
    179.      
    180.     
    181.     }    
    182.     
    183. public function read($filename,$encode='utf-8')    
    184. {    
    185.     
    186.  // ../  一般情况不管处于什么子目录子需要这样子即可 例如appAdminControllersWechatMercharntPayOrderListTodayController.php  
    187.         include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');    
    188.     
    189.         //$this->load ->library('PHPExcel/IOFactory');    
    190.     
    191.         $objReader =IOFactory::createReader('Excel5');    
    192.     
    193.         $objReader->setReadDataOnly(true);    
    194.     
    195.         $objPHPExcel$objReader->load($filename);    
    196.     
    197.         $objWorksheet$objPHPExcel->getActiveSheet();    
    198.     
    199.         $highestRow =$objWorksheet->getHighestRow();    
    200.     
    201.         //echo$highestRow;die;    
    202.     
    203.         $highestColumn = $objWorksheet->getHighestColumn();    
    204.     
    205.         //echo$highestColumn;die;    
    206.     
    207.         $highestColumnIndex =PHPExcel_Cell::columnIndexFromString($highestColumn);    
    208.     
    209.         $excelData =array();    
    210.     
    211.         for($row = 1;$row <= $highestRow$row++) {    
    212.     
    213.             for ($col= 0; $col < $highestColumnIndex$col++) {    
    214.     
    215.                    $excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();    
    216.     
    217.              }    
    218.     
    219.         }    
    220.     
    221.         return $excelData;    
    222.     
    223. }    





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


    第二方法 用集成方法  maatwebsite 集成类,但是不支持一些文件。已经修复

    http://blog.csdn.net/zhwxl_zyx/article/details/47251491 

    并修复其中的问题 

    vendormaatwebsiteexcelsrcMaatwebsiteExcelReadersLaravelExcelReader.php

    修改后的版本

    https://github.com/yanggg1133/Laravel-Excel

    增加 

    [php] view plain copy
    1. /* 
    2. * @desc 返回所有数据 
    3. * @author 绍兴远帆软件有限公司 主营 ewshop网店系统 远帆自动售货机系统 手机话费流量充值系统 票务销售系统 点餐外卖系统 网店进销存系统 
    4. * @website http://www.ewshop.net/ 
    5. * */  
    6. public function readAll()  
    7. {  
    8.   
    9.     // ../  一般情况不管处于什么子目录子需要这样子即可 例如appAdminControllersWechatMercharntPayOrderListTodayController.php  
    10.     //include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');  
    11.   
    12.     //$this->load ->library('PHPExcel/IOFactory');  
    13.   
    14.   
    15.     //$this->reader =IOFactory::createReader('Excel5');  
    16.   
    17.     //$this->reader->setReadDataOnly(true);  
    18.   
    19.     $objPHPExcel$this->excel;  
    20.   
    21.     $objWorksheet$objPHPExcel->getActiveSheet();  
    22.   
    23.     $highestRow =$objWorksheet->getHighestRow();  
    24.   
    25.     //echo$highestRow;die;  
    26.   
    27.     $highestColumn = $objWorksheet->getHighestColumn();  
    28.   
    29.     //echo$highestColumn;die;  
    30.   
    31.     $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);  
    32.   
    33.     $excelData =array();  
    34.   
    35.     for($row = 1;$row <= $highestRow$row++) {  
    36.   
    37.         for ($col= 0; $col < $highestColumnIndex$col++) {  
    38.   
    39.             $excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();  
    40.   
    41.         }  
    42.   
    43.     }  
    44.   
    45.     return $excelData;  
    46.   
    47. }  

    Laravel 4

    "maatwebsite/excel": "~1.3"
    

    Laravel 5

    "maatwebsite/excel": "~2.0"

    [plain] view plain copy
    1. "require-dev": {  
    2.      "fzaninotto/faker": "~1.4",  
    3.      "mockery/mockery": "0.9.*",  
    4.      "phpunit/phpunit": "~4.0",  
    5.      "phpspec/phpspec": "~2.1",  
    6.      "maatwebsite/excel": "~2.0.0"  
    7.  },  


    添加完后执行 composer update


    After updating composer, add the ServiceProvider to the providers array in app/config/app.php

    'MaatwebsiteExcelExcelServiceProvider',
    

    You can use the facade for shorter code. Add this to your aliasses:

    'Excel' => 'MaatwebsiteExcelFacadesExcel',
    

    The class is binded to the ioC as excel

    $excel = App::make('excel');


    Laravel 4

    Laravel Excel includes several config settings for import-, export-, view- and CSV-specific settings. Use the artisan publish command to publish the config file to your project.

    php artisan config:publish maatwebsite/excel
    

    The config files can now be found at app/config/packages/maatwebsite/excel

    Laravel 5

    To publish the config settings in Laravel 5 use:

    php artisan vendor:publish
    

    This will add an excel.php config file to your config folder.


    详细用法请参考官网 http://www.maatwebsite.nl/laravel-excel/docs/getting-started

    1.    "autoload": {   
    2.  
    3.  
    4.          "classmap": [   
    5.  
    6.  
    7.               "database",   
    8.  
    9.  
    10.                "app/libs/phpExcel"   
    11.  
    12.  
    13.           ],   
    14.  
    15.  
    16.       "psr-4": {   
    17.  
    18.  
    19.             "App\": "app/"   
    20.  
    21.  
    22.        } 
    23.  
    24.  
    25. }, 



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


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


    7、在控制器中use PHPExcel


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


         $objPHPExcel = new PHPExcel();


         print_r($objPHPExcel);


    ==========以上是引入phpExcel类步骤(其它第三方类与此类似)============
     
        <span style="font-size:18px;">以下开始excel导入导出</span> 




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


    [php] view plain copy
    1. public function 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.         //Starting the PHPExcel library   
    17.    
    18.         //加载PHPExcel类   
    19.    
    20.        //$this->load->library('PHPExcel');   
    21.    
    22.         //$this->load ->library('PHPExcel/IOFactory');   
    23.    
    24.         $objPHPExcel= new 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.     }   
    99.  
    100.  
    101.  
    102.  
    103.  
    104.  
    105.  
    106.  
    107.  
    108.      控制器中use IOFactory;   use PHPExcel_Cell; 
    109.  
    110.  
    111.  
    112. public function ru(Request $request){   
    113.        $tmp_file =$_FILES ['file_stu'] ['tmp_name'];   
    114.    
    115.        $file_types =explode ( ".", $_FILES ['file_stu'] ['name'] );   
    116.    
    117.        $file_type =$file_types [count ( $file_types ) - 1];   
    118.    
    119.        /*判别是不是.xls文件,判别是不是excel文件*/   
    120.    
    121.        if (strtolower( $file_type ) != "xls"){   
    122.    
    123.           $this->error ( '不是Excel文件,重新上传' );   
    124.    
    125.        }   
    126.    
    127.        $savePath ="./excel/";   
    128.    
    129.        /*以时间来命名上传的文件*/   
    130.    
    131.        $str =date('Ymdhis');   
    132.    
    133.        $file_name =$str . "." . $file_type;   
    134.    
    135.        //echo$file_name;die;   
    136.    
    137.        $request->file('file_stu')->move($savePath, $file_name);   
    138.    
    139.        /*是否上传成功*/   
    140.    
    141.        /*if(!copy($tmp_file,$savePath.$file_name)){  
    142.   
    143.           $this->error ( '上传失败' );  
    144.   
    145.        }*/   
    146.    
    147.        //要获得新的文件路径+名字   
    148.    
    149.        $fullpath =$savePath.$file_name;   
    150.    
    151.        //echo$fullpath;die;   
    152.    
    153.        $re =$this->read($fullpath,'utf-8');   
    154.    
    155.        //print_r($re);die;   
    156.    
    157.        for($i=1;$i<count($re);$i++){   
    158.    
    159.           //print_r($re);   
    160.    
    161.           //echo$re[$i][1];   
    162.    
    163.           $adds =DB::table('goods')->insert(['gname' => $re[$i][1], 'gprice' =>$re[$i][2]]);   
    164.    
    165.        }   
    166.    
    167.        //die;   
    168.    
    169.        if($adds){   
    170.    
    171.             echo"<script>alert('导入成功');location.href='daoru'</script>";   
    172.    
    173.         }else{   
    174.    
    175.             echo"<script>alert('导入失败');location.href='daoru'</script>";   
    176.    
    177.         }   
    178.    
    179.     
    180.    
    181.     }   
    182.    
    183. public function read($filename,$encode='utf-8')   
    184. {   
    185.    
    186.  // ../  一般情况不管处于什么子目录子需要这样子即可 例如appAdminControllersWechatMercharntPayOrderListTodayController.php 
    187.         include_once('../app/libs/phpexcel/phpexcel/IOFactory.php');   
    188.    
    189.         //$this->load ->library('PHPExcel/IOFactory');   
    190.    
    191.         $objReader =IOFactory::createReader('Excel5');   
    192.    
    193.         $objReader->setReadDataOnly(true);   
    194.    
    195.         $objPHPExcel= $objReader->load($filename);   
    196.    
    197.         $objWorksheet= $objPHPExcel->getActiveSheet();   
    198.    
    199.         $highestRow =$objWorksheet->getHighestRow();   
    200.    
    201.         //echo$highestRow;die;   
    202.    
    203.         $highestColumn = $objWorksheet->getHighestColumn();   
    204.    
    205.         //echo$highestColumn;die;   
    206.    
    207.         $highestColumnIndex =PHPExcel_Cell::columnIndexFromString($highestColumn);   
    208.    
    209.         $excelData =array();   
    210.    
    211.         for($row = 1;$row <= $highestRow; $row++) {   
    212.    
    213.             for ($col= 0; $col < $highestColumnIndex; $col++) {   
    214.    
    215.                    $excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();   
    216.    
    217.              }   
    218.    
    219.         }   
    220.    
    221.         return $excelData;   
    222.    
    223. }   





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


    第二方法 用集成方法  maatwebsite 集成类,但是不支持一些文件。已经修复

    http://blog.csdn.net/zhwxl_zyx/article/details/47251491

    并修复其中的问题

    vendormaatwebsiteexcelsrcMaatwebsiteExcelReadersLaravelExcelReader.php

    修改后的版本

    https://github.com/yanggg1133/Laravel-Excel

    增加

    [php] view plain copy
    1. /* 
    2. * @desc 返回所有数据 
    3. * @author 绍兴远帆软件有限公司 主营 ewshop网店系统 远帆自动售货机系统 手机话费流量充值系统 票务销售系统 点餐外卖系统 网店进销存系统 
    4. * @website http://www.ewshop.net/ 
    5. * */ 
    6. public function readAll() 
    7.  
    8.     // ../  一般情况不管处于什么子目录子需要这样子即可 例如appAdminControllersWechatMercharntPayOrderListTodayController.php 
    9.     //include_once('../app/libs/phpexcel/phpexcel/IOFactory.php'); 
    10.  
    11.     //$this->load ->library('PHPExcel/IOFactory'); 
    12.  
    13.  
    14.     //$this->reader =IOFactory::createReader('Excel5'); 
    15.  
    16.     //$this->reader->setReadDataOnly(true); 
    17.  
    18.     $objPHPExcel= $this->excel; 
    19.  
    20.     $objWorksheet= $objPHPExcel->getActiveSheet(); 
    21.  
    22.     $highestRow =$objWorksheet->getHighestRow(); 
    23.  
    24.     //echo$highestRow;die; 
    25.  
    26.     $highestColumn = $objWorksheet->getHighestColumn(); 
    27.  
    28.     //echo$highestColumn;die; 
    29.  
    30.     $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 
    31.  
    32.     $excelData =array(); 
    33.  
    34.     for($row = 1;$row <= $highestRow; $row++) { 
    35.  
    36.         for ($col= 0; $col < $highestColumnIndex; $col++) { 
    37.  
    38.             $excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue(); 
    39.  
    40.         } 
    41.  
    42.     } 
    43.  
    44.     return $excelData
    45.  

    Laravel 4

    "maatwebsite/excel": "~1.3"
    

    Laravel 5

    "maatwebsite/excel": "~2.0"

    [plain] view plain copy
    1. "require-dev": { 
    2.      "fzaninotto/faker": "~1.4", 
    3.      "mockery/mockery": "0.9.*", 
    4.      "phpunit/phpunit": "~4.0", 
    5.      "phpspec/phpspec": "~2.1", 
    6.      "maatwebsite/excel": "~2.0.0" 
    7. }, 


    添加完后执行 composer update


    After updating composer, add the ServiceProvider to the providers array in app/config/app.php

    'MaatwebsiteExcelExcelServiceProvider',
    

    You can use the facade for shorter code. Add this to your aliasses:

    'Excel' => 'MaatwebsiteExcelFacadesExcel',
    

    The class is binded to the ioC as excel

    $excel = App::make('excel');


    Laravel 4

    Laravel Excel includes several config settings for import-, export-, view- and CSV-specific settings. Use the artisan publish command to publish the config file to your project.

    php artisan config:publish maatwebsite/excel
    

    The config files can now be found at app/config/packages/maatwebsite/excel

    Laravel 5

    To publish the config settings in Laravel 5 use:

    php artisan vendor:publish
    

    This will add an excel.php config file to your config folder.


    详细用法请参考官网 http://www.maatwebsite.nl/laravel-excel/docs/getting-started

  • 相关阅读:
    数组的拼接
    numpy的切片和索引
    细说python中的round()方法
    Numpy数组的创建
    快排 [随机数]
    对于归并排序递归的理解
    A1044 Shopping in Mars [连续子序列分割]
    A1085 Perfect Sequence [二分、two pointers]
    快速幂
    [转] 二分法求外接圆最大半径
  • 原文地址:https://www.cnblogs.com/mouseleo/p/8628169.html
Copyright © 2011-2022 走看看