使用 Laravel-Excel 和流的方法导出 Excel
1、使用laravel-excel扩展包导出
扩展包的3.0的版本和2.0相比做了很多的改动,个人感觉更容易使用了。扩展包给出了很多基于query的导出,视图的导出。下面例子为基于array的导出,其他的查看文档即可。
导出类:
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UsersExport implements FromCollection, WithHeadings
{
use Exportable;
private $data;
private $headings;
//数据注入
public function __construct($data, $headings)
{
$this->data = $data;
$this->headings = $headings;
}
//实现FromCollection接口
public function collection()
{
return collect($this->data);
}
//实现WithHeadings接口
public function headings(): array
{
return $this->headings;
}
}
控制器中导出
namespace App\Http\Controllers;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\UsersExport;
class UsersController extends Controller
{
public function export()
{
$data = [
[
'name' => 'cheng',
'email' => 'cheng111'
],
[
'name' => 'cheng',
'email' => 'cheng111'
],
];
$headings = [
'name',
'email'
];
return Excel::download(new UsersExport($data, $headings), 'users.csv');
}
}
2、使用流的形式导出
public function export($params)
{
set_time_limit(0);
$columns = ['字段名'];
$fileName = 'GPS管理明细' . '.csv';
//设置好告诉浏览器要下载excel文件的headers
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'. $fileName .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$fp = fopen('php://output', 'a');//打开output流
mb_convert_variables('GBK', 'UTF-8', $columns);
fputcsv($fp, $columns); //将数据格式化为CSV格式并写入到output流中
$num = $this->getExportNum($params);
$perSize = 2000;//每次查询的条数
$pages = ceil($num / $perSize);
for($i = 1; $i <= $pages; $i++) {
$list = $this->getUnitExportData($params, $i, $perSize);
foreach($list as $item) {
$rowData[] = $this->switchDeviceMakerToDesc($item['device_maker']);
.
.
.
mb_convert_variables('GBK', 'UTF-8', $rowData);
fputcsv($fp, $rowData);
unset($rowData);
}
unset($accessLog);//释放变量的内存
ob_flush(); //刷新输出缓冲到浏览器
flush(); //必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
}
fclose($fp);
exit();
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
不应该是这样的
麻烦问一下,导出图片到 excel 应该怎么处理呢,使用的导出集合
mb_convert_variables('GBK', 'UTF-8', $rowData);??这个作用是啥?