fastadmin导出

1:先上效果图
在这里插入图片描述
2:实现步骤
①在对应的js(路径:/public/assets/js/backend/xxx.js)里添加下图代码
在这里插入图片描述
下面是图中的代码:

$(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("shop/order/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;
                    }
                })
            });
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();
            };

②对应的前段页面导出按钮代码

<a href="javascript:;" class="btn btn-success btn-export {:$auth->check('shop_order/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a>

③对应的后台添加导出方法

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();
    
    //$columns 是得到的字段,可以在这里写上自己的逻辑,比如删除或添加其他要写的字段
    
    $line = 1;
    $list = [];
    $this->model
        ->field($columns)
        ->where($where)
        ->where($whereIds)
        ->chunk(100, function ($items) use (&$list, &$line, &$worksheet) {
            global $userName;
            global $QuyuName;
            $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) {
                    //这样写能防止手机号被excel表格手机号数据自动科学计数,其他同理
                    if($field == "mobile"){
                        $value = " ".$value;
                    }
                    $worksheet->setCellValueByColumnAndRow($col, $line, $value);
                    $worksheet->getColumnDimension('B')->setAutoSize(true);//这样写代表B列自动列宽     
                    $worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                    $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
                    $col++;
                }
            }
        });

//自定义设置表头
$excel->getActiveSheet()->setCellValue(‘A1’,‘ID’);
$excel->getActiveSheet()->setCellValue(‘B1’,‘发起人id’);
// f i r s t = a r r a y k e y s ( first = array_keys( first=arraykeys(list[0]);
// foreach ($first as $index => $item) {
// w o r k s h e e t − > s e t C e l l V a l u e B y C o l u m n A n d R o w ( worksheet->setCellValueByColumnAndRow( 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');exit;
    return;
}

}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值