Fastadmin利用PhpSpreadsheet导出Excel

Php   2025-10-24 10:32   134   0  
 composer require phpoffice/phpspreadsheet   //php版本7.4以上
 composer require phpoffice/phpexcel


JS脚本:

//*************************** 自定义export开始
	      var layerobj = null;
	      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();
				Layer.close(layerobj);
            };
            $(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);
                layerobj = Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("wechat/orderdata/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 + "条)"],
                    //btn: ["选中项(" + ids.length + "条)"],
                    success: function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }
                    , yes: function (index, layero) {
						if(ids.length == 0) return false;
                        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;
                    }
                })
            });
//*************************** 自定义export结束


HTML视图:

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


后台代码:

use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

public function XXX() {
		// 获取当前登录的用户ID
		$islogin = $this->auth->isLogin();
		$isSuperAdmin = $this->auth->isSuperAdmin();
		//$sessionId = session('admin');
		
		if ($islogin && $isSuperAdmin) {
			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 Spreadsheet();

				$excel->getProperties()
					->setCreator("FastAdmin")
					->setLastModifiedBy("FastAdmin")
					->setTitle("FastAdmin")
					->setSubject("FastAdmin");
				$excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
				$excel->getDefaultStyle()->getFont()->setSize(12);

				

				$excel->getDefaultStyle()->applyFromArray(
					array(
						'fill'      => array(
							'type'  => Fill::FILL_SOLID,
							'color' => array('rgb' => '000000')
						),
						'font'      => array(
							'color' => array('rgb' => "000000"),
						),
						'alignment' => array(
							'vertical'   => Alignment::VERTICAL_CENTER,
							'horizontal' => Alignment::HORIZONTAL_CENTER,
							'indent'     => 1
						),
						'borders'   => array(
							'allborders' => array('style' => Border::BORDER_THIN),
						)
					));

				$worksheet = $excel->getActiveSheet();  //获取当前操作sheet的对象
				$worksheet->setTitle(date("YmdHis"));

				$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(
								'color' => array('rgb' => '000000'),
								'size'  => 12,
								'name'  => 'Verdana'
							));
						$list = $items = collection($items)->toArray();

						foreach ($items as $key => $v) {

							foreach ($v as $k => $ele) {
								$tmparray = explode("_text",$k);
								if(count($tmparray)>1){
									$items[$key][$tmparray[0]] = $ele;
									unset($items[$key][$k]);
								}
							}
						}

						foreach ($items as $index => $item) {
							$line++;
							$col = 0;  //设置ID第一列
							foreach ($item as $field => $value) {
								// 实际上应该这样写:
								$cell = $worksheet->getCell(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col) . $line);
								
								$worksheet->setCellValue(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col) . $line, $value);
								//$worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
								//$worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
								$col++;
							}
						}
					});
				$first = array_keys($list[0]);
				foreach ($first as $k => $ele) {
					$tmparray = explode("_text",$ele);
					if(count($tmparray)>1){
						unset($first[$k]);
					}
				}
				
				foreach ($first as $index => $item) {
					//$index+1设置ID字段在第一列
					$worksheet->setCellValue(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($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 = IOFactory::createWriter($excel, 'Xlsx');
				$objWriter->save('php://output');
				
				return;
			}
		} else {
			exit('没有权限下载数据,请联系管理员!');
		}
    }