【Laravel】使用phpoffice/phpspreadsheet导入导出数据

一、安装PHPExcel

1.下载:PHPExcel  https://github.com/PHPOffice/PHPExcel 

2.解压后:Classes文件夹改名为PHPExcel 

3.把文件夹PHPExcel 放到根目录vendor文件夹下

或者

1、composer安装:

composer require phpoffice/phpspreadsheet

二、控制器引用

use \PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;

二、导出方法

public function expor(Request $request)
{

  //导入模板
$spreadsheet = IOFactory::load(public_path(‘excel/exportOrder.xls‘));
$spreadsheet->getActiveSheet()->setTitle(‘信息导出‘);
$i = 1;
  //默认填充数据
        $explame_data_list = array(
            array(
                ‘bank_deal_no‘ => ‘1234567890123456‘,
                ‘account_name‘ => ‘小明‘,
                ‘bank_card‘ => ‘4231456987436654‘,
                ‘deal_money‘ => ‘100.00‘,
                ‘deal_time‘ => date("Y-m-d H:i:s"),
            ),
        );

        //第二行起
        $baseRow = 2; //数据从N-1行开始往下输出 这里是避免头信息被覆盖
        foreach ($explame_data_list as $k => $val) {
            $i = $k + $baseRow;
            $worksheet->setCellValue(‘A‘ . $i, $val[‘bank_deal_no‘]);
            $worksheet->setCellValue(‘B‘ . $i, $val[‘account_name‘]);
            $worksheet->setCellValue(‘C‘ . $i, $val[‘bank_card‘]);
            $worksheet->setCellValue(‘D‘ . $i, $val[‘deal_money‘]);
            $worksheet->setCellValue(‘E‘ . $i, $val[‘deal_time‘]);;
        }
        //处理 数字过大会进行科学计数法
        $worksheet->getStyle(‘A2‘)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER);
        $worksheet->getStyle(‘C2‘)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER)
    header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet‘);
header(‘Content-Disposition: attachment;filename="订单导出.xls"‘);
$writer = IOFactory::createWriter($spreadsheet, ‘Xlsx‘);
$writer->save(‘php://output‘);
}

【Laravel】使用phpoffice/phpspreadsheet导入导出数据

上一篇:vue将html导出为pdf


下一篇:Nodejs搭建web服务器