PHP建站技术分享-从入门到精通PHP建站技术分享-从入门到精通PHP建站技术分享-从入门到精通

QQ:420220301 微信/手机:150-3210-7690
当前位置:首页 > CMS教程 > Fastadmin

导出excle带图片

管理员 2024-12-14
Fastadmin
8

根据$columns导出字段字段,自动识别图片并导出。
安装依赖 composer require phpoffice/phpexcel
对应的前段页面导出按钮代码

在对应的js(路径:/public/assets/js/backend/xxx.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("company/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;                    }                })        });

注意要修改Fast.api.fixurl的路径;
控制器代码如下:
protected $abc = [

    0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', 8 => 'I', 9 => 'J',    10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T',    20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'AA', 27 => 'AB', 28 => 'AC', 29 => 'AD',    30 => 'AE', 31 => 'AF', 32 => 'AG', 33 => 'AH', 34 => 'AI', 35 => 'AJ', 36 => 'AK', 37 => 'AL', 38 => 'AM', 39 => 'AN',    40 => 'AO', 41 => 'AP', 42 => 'AQ', 43 => 'AR', 44 => 'AS', 45 => 'AT', 46 => 'AU', 47 => 'AV', 48 => 'AW', 49 => 'AX',    50 => 'AY', 51 => 'AZ', 52 => 'BA', 53 => 'BB', 54 => 'BC', 55 => 'BD', 56 => 'BE', 57 => 'BF', 58 => 'BG', 59 => 'BH',    60 => 'BI', 61 => 'BJ', 62 => 'BK', 63 => 'BL', 64 => 'BM', 65 => 'BN', 66 => 'BO', 67 => 'BP', 68 => 'BQ', 69 => 'BR',    70 => 'BS', 71 => 'BT', 72 => 'BU', 73 => 'BV', 74 => 'BW', 75 => 'BX', 76 => 'BY', 77 => 'BZ', 78 => 'CA', 79 => 'CB',    80 => 'CC', 81 => 'CD', 82 => 'CE', 83 => 'CF', 84 => 'CG', 85 => 'CH', 86 => 'CI', 87 => 'CJ', 88 => 'CK', 89 => 'CL',    90 => 'CM', 91 => 'CN', 92 => 'CO', 93 => 'CP', 94 => 'CQ', 95 => 'CR', 96 => 'CS', 97 => 'CT', 98 => 'CU', 99 => 'CV'];

/**

 * 导出excel 带图片 */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');        //带出字段,必须有id        $columns = 'id,nickname,mobile,bio,status,createtime';        $height = 20;//通用行高        $pic_height = 40;//图片行高        $objPHPExcel = new PHPExcel();        $objActSheet = $objPHPExcel->getActiveSheet();        //设置标题        $title = explode(',', $columns);        $bold = count($title);        $objPHPExcel->getActiveSheet()->getStyle('A:'. $this->abc[$bold - 1])->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//列a至列n 垂直居中        $objPHPExcel->getActiveSheet()->getStyle('A:'. $this->abc[$bold - 1])->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//列a至列n水平居中        $objPHPExcel->getActiveSheet()->getStyle('A1:'. $this->abc[$bold - 1] .'1')->getFont()->setBold(true);        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight($height);//头部第一行 行高        foreach ($title as $k => $v) {            if ($v != 'id') {//无id版本 如若改为有id版本,删除此处$k --;全局搜‘无id版本’,再修改两处。                $k --;                $objActSheet->setCellValue($this->abc[$k] . '1', __($v));//$objActSheet->setCellValue('A1', '编号');                // 设置列宽度                $objPHPExcel->getActiveSheet()->getColumnDimension($this->abc[$k])->setWidth(17);            }        }        $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();      //自定义模型(手动创建),使用fastadmin创建的模型会有很多多余字段。        Exportuser::field($columns)            ->where($where)            ->where($whereIds)            ->chunk(100, function ($items) use (&$objPHPExcel, $title, &$objActSheet, &$pic, $pic_height) {                $data = $items = collection($items)->toArray();                //自定义数据格式区域                foreach ($data as &$val) {                    $val['mobile'] = " " . $val['mobile'];                    $val['status'] = $val['status'] == 'normal' ? '营业' : '歇业';                    $val['createtime'] = datetime($val['createtime'], "Y-m-d H:i:s");                }                unset($val);                foreach ($data as $k => $v) {                    $k += 2;                    $objPHPExcel->setActiveSheetIndex(0);                    $objPHPExcel->getActiveSheet()->setTitle('Simple');                    // 表格高度                    $objActSheet->getRowDimension($k)->setRowHeight(30);                    $pics = ['id'];//记录图片字段                    $types = ['gif', 'jpeg', 'png', 'bmp', 'peg', 'jpg']; //定义检查的图片类型                    //记录图片列表                    $num = -2;// 无id版本 有id设置为0                    $pic = [];                    foreach ($v as $pick => $picv) {                        $num ++;                        if (in_array(substr($picv, strrpos($picv, '.') + 1), $types)) {                            $pic[$pick] = $this->abc[$num];//记录图片的列表                            //记录图片字段                            $pics[$pick] = $picv;                            $v[$pick] = thinkRequest::instance()->domain() . $v[$pick];//拼接域名                            $data[$k][$pick] = $v[$pick];                            // 图片生成                            $objDrawing[$k] = new PHPExcel_Worksheet_MemoryDrawing();                            // 截取图片的格式,用不同的方法                            $end[$k] = substr($data[$k][$pick], strrpos($data[$k][$pick], '.') + 1);                            if ($end[$k] == 'jpg' || $end[$k] == 'peg') {                                $img[$k] = @imagecreatefromjpeg($data[$k][$pick]);                            } else if ($end[$k] == 'png') {                                $img[$k] = @imagecreatefrompng($data[$k][$pick]);                            } else if ($end[$k] == 'gif') {                                $img[$k] = @imagecreatefromgif($data[$k][$pick]);                            }                            $objDrawing[$k]->setImageResource($img[$k]);                            $objDrawing[$k]->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);//渲染方法                            $objDrawing[$k]->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);                            // // 设置宽度高度                            $objDrawing[$k]->setHeight(40);//照片高度                            $objDrawing[$k]->setWidth(40); //照片宽度                            // /*设置图片要插入的单元格*/                            //$objDrawing[$k]->setCoordinates('G' . $k);                            $objDrawing[$k]->setCoordinates($pic[$pick] . $k);                            // // 图片偏移距离                            $objDrawing[$k]->setOffsetX(8);                            $objDrawing[$k]->setOffsetY(8);                            $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());                            // 表格高度                            $objActSheet->getRowDimension($k)->setRowHeight($pic_height);                        }                    }                    //渲染数据                    foreach ($title as $i => $j) {                        if (!isset($pics[$j])) {                            //无id版本                            if ($this->abc[$i] != 'A') {                                $objActSheet->setCellValue($this->abc[--$i] . $k, $v[$j]);//$objActSheet->setCellValue('A' . $k, $v['id']);                            }

// $objActSheet->setCellValue($this->abc[$i] . $k, $v[$j]);//有id版本

                        }                    }                }            });        $fileName = '质保公司管理';        $date = date("Y-m-d", time());        $fileName .= "_{$date}.xls";        $fileName = iconv("utf-8", "gb2312", $fileName);        $objPHPExcel->setActiveSheetIndex(0);        header('Content-Type: application/vnd.ms-excel');        header("Content-Disposition: attachment;filename="$fileName"");        header('Cache-Control: max-age=0');        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');        $objWriter->save('php://output'); //文件通过浏览器下载        return;    }}

希望以上内容对你有所帮助!如果还有其他问题,请随时提问。 各类知识收集 拥有多年CMS企业建站经验,对 iCMS, Fastadmin, ClassCMS, LeCMS, PbootCMS, PHPCMS, 易优CMS, YzmCMS, 讯睿CMS, 极致CMS, Wordpress, HkCMS, YznCMS, WellCMS, ThinkCMF, 等各类cms的相互转化,程序开发,网站制作,bug修复,程序杀毒,插件定制都可以提供最佳解决方案。

扫码关注

qrcode

QQ交谈

回顶部