此文已经不适用于最新版本的FastAdmin导出使用,只适用于2018年FastAdmin的版本。
最新版本FastAdmin请参考:https://ask.fastadmin.net/article/12048.html
在FastAdmin列表中的导出功能在执行导出时是将数据重新渲染到页面后再进行导出操作,这一切均在客户端进行的,这就会产生一个问题,如果数量量太大,会导致浏览器假死,这是我们不希望得到的结果。其次客户端导出不能很好的控制我们的数据格式和数据字段,此时我们可以启用服务端导出。
控制器添加export
方法
首先们得在我们的控制器添加一个export
导出方法,如下:
public function export() { if ($this->request->isPost()) { set_time_limit(0); $search = $this->request->post('search'); $ids = $this->request->post('ids'); $filter = $this->request->post('filter'); $op = $this->request->post('op'); $columns = $this->request->post('columns'); $excel = new PHPExcel(); $excel->getProperties() ->setCreator("FastAdmin") ->setLastModifiedBy("FastAdmin") ->setTitle("标题") ->setSubject("Subject"); $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei'); $excel->getDefaultStyle()->getFont()->setSize(12); $this->sharedStyle = new PHPExcel_Style(); $this->sharedStyle->applyFromArray( array( 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '000000') ), 'font' => array( 'color' => array('rgb' => "000000"), ), 'alignment' => array( 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'indent' => 1 ), 'borders' => array( 'allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN), ) )); $worksheet = $excel->setActiveSheetIndex(0); $worksheet->setTitle('标题'); $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]]; $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]); list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $line = 1; $list = []; $this->model ->field($columns) ->where($where) ->where($whereIds) ->chunk(100, function ($items) use (&$list, &$line, &$worksheet) { $styleArray = array( 'font' => array( 'bold' => true, 'color' => array('rgb' => 'FF0000'), 'size' => 15, 'name' => 'Verdana' )); $list = $items = collection($items)->toArray(); foreach ($items as $index => $item) { $line++; $col = 0; foreach ($item as $field => $value) { $worksheet->setCellValueByColumnAndRow($col, $line, $value); $worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT); $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray); $col++; } } }); $first = array_keys($list[0]); foreach ($first as $index => $item) { $worksheet->setCellValueByColumnAndRow($index, 1, __($item)); } $excel->createSheet(); // Redirect output to a client’s web browser (Excel2007) $title = date("YmdHis"); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $title . '.xlsx"'); 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($excel, 'Excel2007'); $objWriter->save('php://output'); return; } }
这段话大概意思就是根据我们的条件构造我们需要导出的数据,采用的是PHPExcel的方法进行导出。
添加导出按钮
接下我们需要在视图中添加一个导出按钮,我们将按钮添加到导入按钮旁边,代码如下:
<a href="javascript:;" class="btn btn-success btn-export {:$auth->check('test/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a>
JS添加事件
接下来需要在控制器对应的JS中添加以下代码,用于提交导出事件。
var submitForm = function (ids, layero) { var options = table.bootstrapTable('getOptions'); console.log(options); var columns = []; $.each(options.columns[0], function (i, j) { if (j.field && !j.checkbox && j.visible && j.field != 'operate') { columns.push(j.field); } }); var search = options.queryParams({}); $("input[name=search]", layero).val(options.searchText); $("input[name=ids]", layero).val(ids); $("input[name=filter]", layero).val(search.filter); $("input[name=op]", layero).val(search.op); $("input[name=columns]", layero).val(columns.join(',')); $("form", layero).submit(); }; $(document).on("click", ".btn-export", function () { var ids = Table.api.selectedids(table); var page = table.bootstrapTable('getData'); var all = table.bootstrapTable('getOptions').totalRows; console.log(ids, page, all); Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("test/export") + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", { title: '导出数据', btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"], success: function (layero, index) { $(".layui-layer-btn a", layero).addClass("layui-layer-btn0"); } , yes: function (index, layero) { submitForm(ids.join(","), layero); return false; } , btn2: function (index, layero) { var ids = []; $.each(page, function (i, j) { ids.push(j.id); }); submitForm(ids.join(","), layero); return false; } , btn3: function (index, layero) { submitForm("all", layero); return false; } }) });
效果图
我们可以仅导出选择项、本页数据或全部数据。
希望以上内容对你有所帮助!如果还有其他问题,请随时提问。 各类知识收集 拥有多年CMS企业建站经验,对 iCMS, Fastadmin, ClassCMS, LeCMS, PbootCMS, PHPCMS, 易优CMS, YzmCMS, 讯睿CMS, 极致CMS, Wordpress, HkCMS, YznCMS, WellCMS, ThinkCMF, 等各类cms的相互转化,程序开发,网站制作,bug修复,程序杀毒,插件定制都可以提供最佳解决方案。