> 有時候應用里會用到Excel導出,PHP做csv文件的導出比較簡單,但Excel就比較復雜,這里推薦使用yii2的excel插件。
官網:https://github.com/PHPOffice/PHPExcel
[TOC]
#### 下載Excel插件
~~~
composer require phpoffice/phpexcel "*" -v
~~~
#### 參考Example代碼:
~~~
/vendor/phpoffice/phpexcel/Examples/01simple-download-xls.php
//將該代碼拷入Controller里運行即可,由于他的方法使用起來不是很方便,這里我選擇封裝方法,便于下次使用。
~~~
#### 封裝方法:
~~~
/**
* @DESC 數據導
* @example
* $data = [[1, "小明", "25"],[2, "王琨", "22"]];
* $header = ["id", "姓名", "年齡"];
* Myhelpers::exportEXCEL($data, $header);
* @return void, Browser direct output
*/
static function exportEXCEL($data, $header, $title = "simple", $filename = "data"){
if (!is_array($data) || !is_array($header)) return false;
$objPHPExcel = new \PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
//設置表頭,也就是第一行數據
foreach ($header as $k => $v){
$column = \PHPExcel_Cell::stringFromColumnIndex($k);
$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($column."1", $v);
}
//設置行數據,從第二行開始
foreach ($data as $key=>$item){
foreach ($item as $key2=>$val){
$column = \PHPExcel_Cell::stringFromColumnIndex($key2); //獲得列位置
// 添加一行數據,A1、B1、C1.....N1的各個數據
//設置為$key+2,因為key是從0開始,而我們的行數據第一個索引是“1”,而上面因為設置了表頭,占了一行數據,所以就直接+2
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($column.($key+2), $val);
}
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle($title);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
~~~
- 基礎教程
- 入門安裝
- Yii2 composer 安裝慢解決
- Cookies
- 數據庫操作
- 數據提供者
- 助手類
- 驗證規則
- GridView
- DetailView
- YII2分頁
- JS、CSS的引用
- Excel導出
- 中文轉拼音
- 發送郵件
- 第三方插件
- Session跨域共享
- Url跨域訪問
- 場景應用
- 查詢條件鏈
- Session分布式共享
- Redis的使用
- mongodb
- 高級教程
- 自定義gii模板
- 角色權限管理(RBAC)
- user組件的配置
- 國際化(I18N)
- 小部件(Widget)
- 模塊(Module)
- 行為(Behavior)
- 緩存(Cache)
- migrate 數據庫遷移
- phpstorm
- 快捷鍵
- 自定義
- 其它插件