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

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

使用PhpSpreadsheet进行服务端导出

管理员 2024-12-14
Fastadmin
36

Karson老大在论坛发布过使用PHPExcel在服务端进行导出的帖子,帖子如下:

使用PHPExcel进行服务端导出

服务端导出比前端导出性能更优,导出内容可控,样式可自定义
但是因为PHPExcel停止更新的原因,新版本已切换到PhpSpreadsheet了,但是老大的教程并未更新,论坛上也未找到有相关帖子,于是自己改了一版并分享出来。

其它步骤和原帖一致,只是Controlle的代码更新了,其中有一段数据的处理,将下拉列表生成的值合并,例如:status字段为1时,生成为status_text为“正常”,即将stauts更新为“正常”并删掉status_text字段。

类库引用:

use PhpOfficePhpSpreadsheetSpreadsheet;use PhpOfficePhpSpreadsheetWriterXlsx;use PhpOfficePhpSpreadsheetIOFactory;use PhpOfficePhpSpreadsheetStyleFill;use PhpOfficePhpSpreadsheetStyleColor;use PhpOfficePhpSpreadsheetStyleAlignment;use PhpOfficePhpSpreadsheetStyleBorder;use PhpOfficePhpSpreadsheetStyleNumberFormat;

控制器方法

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 Spreadsheet();            $excel->getProperties()                ->setCreator("FastAdmin")                ->setLastModifiedBy("FastAdmin")                ->setTitle("标题")                ->setSubject("Subject");            $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->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(                            '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;                        foreach ($item as $field => $value) {                            $worksheet->setCellValueByColumnAndRow($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) {                $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 = IOFactory::createWriter($excel, 'Xlsx');            $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交谈

回顶部