laravel框架實現phpExcel導入導出


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類步驟(其它第三方類與此類似)============

<span style="font-size:18px;">以下開始excel導入導出</span>


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

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;

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導入導出終於完成了,趕快嘗試一下吧!





注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: