官方导出文档
laravel-admin自带的导出excel会导出与此模型关联的其他数据。所以参考官方文档调整代码
文章表:id,title,user_id
用户表:id,username
//文章模型关联用户
public function user(){
return $this->belongsTo(User::class, 'user_id', 'id');
}
filename = $filename;
}
public function setAttr($head, $body){
$this->head = $head;
$this->body = $body;
}
public function export()
{
Excel::create($this->filename, function($excel) {
$excel->sheet('sheet1', function($sheet) {
// 这段逻辑是从表格数据中取出需要导出的字段
$head = $this->head;
$body = $this->body;
//init列
$title_array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH'];
$rows = collect([$head]); //写入标题
$sheet->rows($rows);
collect( $this->getData() )->map( function ($item,$k)use($body,$sheet,$title_array ) {
foreach ($body as $i=>$keyName){
if($keyName == 'pic' && file_exists(array_get($item, $keyName)) ) { //判断图片列,图片存在,如果是则放图片
$objDrawing = new PHPExcel_Worksheet_Drawing;
$v = public_path('/'). array_get($item, $keyName); //拼接图片地址
//dd($v);
$objDrawing->setPath( $v );
$sp = $title_array[$i];
$objDrawing->setCoordinates( $sp . ($k+2) );
$sheet->setHeight($k+2, 65); //设置高度
$sheet->setWidth(array( $sp =>30)); //设置宽度
$objDrawing->setHeight(80);
$objDrawing->setOffsetX(1);
$objDrawing->setRotation(1);
$objDrawing->setWorksheet($sheet);
} else { //否则放置文字数据
$v = array_get($item, $keyName);
$sheet->cell($title_array[$i] . ($k+2), function ($cell) use ($v) {
$cell->setValue($v);
});
}
}
});
});
})->export('xls');
}
}
使用方法:
$excel = new ExcelExpoter('文章列表');
$excel->setAttr(['id', '名称', '类型', '图片'], ['id', 'title', 'user.title', 'pic']);
$grid->exporter($excel);
参考:
http://blog.guansixu.cn/post/laravel-admin-export.html
https://www.cnblogs.com/kkform/p/8962149.html
导出图片 : http://www.cnblogs.com/lxwphp/p/9804651.html