日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Thinkphp 正文

TP5使用Composer安裝PhpSpreadsheet類庫實現導出Excel表并封裝方法

更新時間: 2019-02-25 Thinkphp

一、背景介紹:

PhpSpreadsheet是PHPExcel的下一個版本。它打破了兼容性,大大提高了代碼庫質量(命名空間,PSR合規性,最新PHP語言功能的使用等)。

由于所有努力都轉移到了PhpSpreadsheet,因此將不再維護PHPExcel。PHPExcel,補丁和新功能的所有貢獻都應該針對PhpSpreadsheet開發分支。

前提:TP5項目中已經安裝配置好Composer 管理工具包。

 

二、Composer 中文網 / Packagist 中國全量鏡像:https://www.phpcomposer.com/  打開安裝包列表搜索phpspreadsheet;

資源鏈接:https://packagist.org/packages/phpoffice/phpspreadsheet   

復制命令composer require phpoffice/phpspreadsheet
PHP需要安裝fileinfo擴展

在開發工具(比如:PHPSTORM)命令行(terminal)中執行;
三、創建Office類文件并封裝,在需要導出Excel表的地方引入即可: 

 
namespace app\index\controller;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Office
{

/**
* 導出excel表
* $data:要導出excel表的數據,接受一個二維數組
* $name:excel表的表名
* $head:excel表的表頭,接受一個一維數組
* $key:$data中對應表頭的鍵的數組,接受一個一維數組
* 備注:此函數缺點是,表頭(對應列數)不能超過26;
*循環不夠靈活,一個單元格中不方便存放兩個數據庫字段的值
*/
public function outdata($name='測試表', $data=[], $head=[], $keys=[])
{
$count = count($head); //計算表頭數量

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

for ($i = 65; $i < $count + 65; $i++) { //數字轉字母從65開始,循環設置表頭:
$sheet->setCellValue(strtoupper(chr($i)) . '1', $head[$i - 65]);
}

/*--------------開始從數據庫提取信息插入Excel表中------------------*/


foreach ($data as $key => $item) { //循環設置單元格:
//$key+2,因為第一行是表頭,所以寫到表格時 從第二行開始寫

for ($i = 65; $i < $count + 65; $i++) { //數字轉字母從65開始:
$sheet->setCellValue(strtoupper(chr($i)) . ($key + 2), $item[$keys[$i - 65]]);
$spreadsheet->getActiveSheet()->getColumnDimension(strtoupper(chr($i)))->setWidth(20); //固定列寬
}

}

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');

//刪除清空:
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
} }

調用示例: 

$excel = new Office();

//設置表頭:
$head = ['訂單編號', '商品總數', '收貨人', '聯系電話', '收貨地址'];

//數據中對應的字段,用于讀取相應數據:
$keys = ['order_sn', 'num', 'consignee', 'phone', 'detail'];

$excel->outdata('訂單表', $orders, $head, $keys);


 


欄目分類
最近更新