1. 程式人生 > >php操作Excel

php操作Excel

autoload required lesson off enable 圖片 space ace val

學習地址:

http://www.houdunren.com/houdunren18_lesson_240

插件下載地址:

https://packagist.org/?query=phpoffice

技術分享圖片

下載插件:

composer require phpoffice/phpspreadsheet 技術分享圖片


手冊地址:

https://phpspreadsheet.readthedocs.io/en/develop/

環境要求:

Software requirements

The following software is required to develop using PhpSpreadsheet:

  • PHP version 5.6 or newer
  • PHP extension php_zip enabled
  • PHP extension php_xml enabled
  • PHP extension php_gd2 enabled (if not compiled in)

檢測環境:

 1 <?php
 2 /**
 3  * Created by Haima.
 4  * Author:Haima
 5  * QQ:228654416
 6  * Date: 2018/7/22
 7  * Time: 9:35
 8  */
 9 
10 require ‘vendor/autoload.php‘;
11 
12 /**
13  * 環境檢測
14
*/ 15 16 var_dump(PHP_VERSION); 17 var_dump(extension_loaded(‘zip‘)); 18 var_dump(extension_loaded(‘xml‘)); 19 var_dump(extension_loaded(‘gd‘));

可以看到環境沒有問題

技術分享圖片


寫入數據並保存為Excel文件:

 1 <?php
 2 /**
 3  * Created by Haima.
 4  * Author:Haima
 5  * QQ:228654416
 6  * Date: 2018/7/22
 7  * Time: 9:35
 8  */
9 10 require ‘vendor/autoload.php‘; 11 12 ///** 13 // * 環境檢測 14 // */ 15 // 16 //var_dump(PHP_VERSION); 17 //var_dump(extension_loaded(‘zip‘)); 18 //var_dump(extension_loaded(‘xml‘)); 19 //var_dump(extension_loaded(‘gd‘)); 20 21 22 use PhpOffice\PhpSpreadsheet\Spreadsheet; 23 use PhpOffice\PhpSpreadsheet\Writer\Xlsx; 24 25 $spreadsheet = new Spreadsheet(); 26 $spreadsheet->setActiveSheetIndex(0); //設置要操作的表單頁Sheet,傳入一個索引 27 $sheet = $spreadsheet->getActiveSheet(); //獲取當前要操作的表單 28 29 //設置表頭 30 $sheet->setCellValue(‘A1‘, ‘編號‘) 31 ->setCellValue(‘B1‘,‘用戶名‘) 32 ->setCellValue(‘B1‘,‘昵稱‘) 33 ->setCellValue(‘B1‘,‘年齡‘); 34 35 //要寫入的數據 36 $data = [ 37 [ 38 ‘uid‘ =>1, 39 ‘username‘ =>‘lisi‘, 40 ‘nickname‘ =>‘李四‘, 41 ‘age‘ =>18 42 ], 43 [ 44 ‘uid‘ =>2, 45 ‘username‘ =>‘wangwu‘, 46 ‘nickname‘ =>‘王五‘, 47 ‘age‘ =>19 48 ], 49 [ 50 ‘uid‘ =>3, 51 ‘username‘ =>‘mailiu‘, 52 ‘nickname‘ =>‘麻六‘, 53 ‘age‘ =>20 54 ] 55 ]; 56 $sheet->fromArray($data,null,‘A2‘); //從A2行開始寫入數據 57 $writer = new Xlsx($spreadsheet); 58 $writer->save(‘ReadData.xlsx‘); //設置保存文件名稱

效果:

技術分享圖片

php操作Excel