Dcat-admin添加Excel导入功能
Laravel  /  管理员 发布于 3年前   3482
之前我用laravel-admin实现了导入导出功能,有兴趣的可以去看看
https://www.zongscan.com/demo333/174.html
今天看到这篇就收集记录一下,基本大同小异
Dcat Admin 中文文档:
https://learnku.com/docs/dcat-admin/2.x
DcatAdmin简单实现导入Excel:
前提
安装 dcat/easy-excel
composer require dcat/easy-excel
或者你想用 maatwebsite/excel 之类的其他的工具也可以,差不太多看个人喜好
实现
新建一个工具表单,用来上传 Excel
<?php
namespace App\Admin\Forms;
use Dcat\EasyExcel\Excel;
use Dcat\Admin\Widgets\Form;
class TestImportForm extends Form
{
/**
* Handle the form request.
*
* @param array $input
*
* @return \Dcat\Admin\Http\JsonResponse
*/
public function handle(array $input)
{
// 获取上传的文件路径
$file_path = storage_path('app/public' . $input['import_file']);
// 如果用的是maatwebsite/excel或者其他, 把读取数据这一步改改就好了
// 读取excel文件
$data = Excel::import($file_path)->toArray();
// [
// "Sheet1" => [
// 2 => [
// "姓名" => "张三",
// "电话" => 123456789,
// ],
// 3 => [
// "姓名" => "李四",
// "电话" => 987654321,
// ],
// ],
// ]
// 处理数据
//...
// 入库
//...
return $this->response()->success('ok')->refresh();
}
/**
* Build a form here.
*/
public function form()
{
// 禁用重置表单按钮
$this->disableResetButton();
// 文件上传
$this->file('import_file', ' ')
->disk('public')
->accept('xls,xlsx')
->uniqueName()
->autoUpload()
->move('/import')
->help('支持xls,xlsx');
}
}
新建一个 Action, 用来下载导入模板
<?php
namespace App\Admin\Actions;
use Dcat\Admin\Actions\Action;
use Dcat\Admin\Actions\Response;
/**
* 下载导入模板
* Class DownloadTemplate
*
* @package App\Admin\Actions
*/
class DownloadTemplate extends Action
{
/**
* @return string
*/
protected $title = '<button class="btn btn-primary"><i class="feather icon-download"></i> 下载导入模板</button>';
/**
* Handle the action request.
*
* @return Response
*/
public function handle()
{
return $this->response()->download('你的导入模板.xlsx');
}
}
在列表增加操作按钮
/**
* Make a grid builder.
*
* @return Grid
*/
protected function grid()
{
return Grid::make(new User(), function (Grid $grid) {
// 在工具栏添加操作按钮,用于上传Excel文件及下载导入模板
$grid->tools(function (Grid\Tools $tools) {
$tools->append(Modal::make()
// 大号弹窗
->lg()
// 弹窗标题
->title('上传文件')
// 按钮
->button('<button class="btn btn-primary"><i class="feather icon-upload"></i> 导入数据</button>')
// 弹窗内容
->body(TestImportForm::make()));
// 下载导入模板
$tools->append(DownloadTemplate::make()->setKey('test_question'));
});
$grid->column('id')->sortable();
$grid->column('name');
$grid->column('email');
// ...
});
}
转:
https://learnku.com/articles/67058
效果图:
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号