Utilice phpExcel en fastadmin para exportar datos de la tabla a sobresalir

Aunque la tabla en fastadmin viene con excel de exportación, eso no es fácil de usar. Cada vez que haces clic en exportar, la tabla se actualiza. Los datos de los últimos siete días están predeterminados. Entonces, desesperado, tengo que encontrar otra manera . No digas tonterías, entonces hablemos sobre el uso de phpExcel:

Uno, descarga phpExcel

clon de git https://github.com/PHPOffice/PHPExcel

Una vez finalizado, aparecerán las siguientes carpetas 

 El directorio interno de esta carpeta renombrada es el siguiente:

 En segundo lugar, copie la carpeta PHPExcel incluida en la imagen de arriba a su proyecto

 En tercer lugar, agregue un método de exportación a su controlador:

 /**
             * 导出EXCEL
             */
            public function export()
            {
                //查询数据库信息
                try {
                    $xlsData = Db::table('fw_goods')->select();
                } catch (\Exception $e) {
                    return $e->getMessage();
                }
                Vendor('PHPExcel.PHPExcel');//调用类库,路径是基于vendor文件夹的
                Vendor('PHPExcel.PHPExcel.Worksheet.Drawing');
                Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
                //实例化
                $objExcel = new \PHPExcel();
                //设置文档属性
                $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
                //设置内容
                $objActSheet = $objExcel->getActiveSheet();
                $key = ord("A");
                $letter = explode(',', "A,B,C,D,E,F");
                $arrHeader = array('时间', '当日扫码量', '当日预警量', '当日无效码量');
                //填充表头信息
                $lenth = count($arrHeader);
                for ($i = 0; $i < $lenth; $i++) {
                    $objActSheet->setCellValue("$letter[$i]1", "$arrHeader[$i]");
                };
                //填充表格信息
                foreach ($xlsData as $k => $v) {
                    $k += 2;
                    //表格内容
                    $objActSheet->setCellValue('A' . $k, $v['id']);
                    $objActSheet->setCellValue('B' . $k, $v['company_id']);
                    $objActSheet->setCellValue('C' . $k, $v['name']);
                    $objActSheet->setCellValue('D' . $k, date('Y-m-d H:i:s', $v['createtime']));
                    $objActSheet->setCellValue('E' . $k, $v['goods_images']);
                    // 图片生成
                    //$objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
                    //$objDrawing[$k]->setPath(ROOT_PATH."public/static/image/playbtn.png");
                    // 设置宽度高度
                    //$objDrawing[$k]->setHeight(40);//照片高度
                    //$objDrawing[$k]->setWidth(40); //照片宽度
                    // 设置图片要插入的单元格
                    //$objDrawing[$k]->setCoordinates('C' . $k);
                    // 图片偏移距离
                    //$objDrawing[$k]->setOffsetX(30);
                    //$objDrawing[$k]->setOffsetY(12);
                    //$objDrawing[$k]->setWorksheet($objExcel->getActiveSheet());

                    // 表格高度
                    $objActSheet->getRowDimension($k)->setRowHeight(20);
                }

                $width = array(20, 20, 15, 10, 10, 30, 10, 15);
                //设置表格的宽度
                $objActSheet->getColumnDimension('A')->setWidth($width[5]);
                $objActSheet->getColumnDimension('B')->setWidth($width[1]);
                $objActSheet->getColumnDimension('C')->setWidth($width[0]);
                $objActSheet->getColumnDimension('D')->setWidth($width[5]);
                $objActSheet->getColumnDimension('E')->setWidth($width[5]);

                $outfile = md5("扫码明细" . time()) . ".xlsx";
                ob_end_clean();
                header("Content-Type: application/force-download");
                header("Content-Type: application/octet-stream");
                header("Content-Type: application/download");
                header('Content-Disposition:inline;filename="' . $outfile . '"');
                header("Content-Transfer-Encoding: binary");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Pragma: no-cache");
                $objWriter->save('php://output');
            }

Cuatro: agregue un botón de exportación a su página html:

<a href="javascript:;" style="float: right;margin-top: 10px;" class="btn btn-success btn-export {:$auth->check('data/barcodedata/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a>

Cinco: llame al método de exportación en su archivo js:

Tenga en cuenta que debe usar window.location.href, no use la solicitud ajax, de lo contrario el navegador no aparecerá en la barra de descarga, este problema se ha escrito en mi blog anterior, puede leerlo si está interesado. 

El método de exportación se refiere a https://blog.csdn.net/adorablewolf/article/details/88394160

Supongo que te gusta

Origin blog.csdn.net/qq_41588568/article/details/109000580
Recomendado
Clasificación