Phpspreadsheet 导入导出功能

安装Composer官网链接https://phpspreadsheet.readthedocs.io/en/latest/faq/

https://getcomposer.org/Composer-Setup.exe

开启phpfile拓展php.ini这行;extension=fileinfo改为:

extension=fileinfo

根目录安装Phpspreadsheet

composer require phpoffice/phpspreadsheet

前端js请求生成跳转请求

var link=document.createElement('a');
 document.body.appendChild(link);
 link.href="";
 link.click();

后端代码

select()
        ->toArray();
    if(empty($data))
    {
        $this->error('你要导出的数据是空的哇!',url('index'));
    }
    $title = [
        'id','date' //具体字段根据自己需要来设置
    ];*/
    $spreadsheet = new Spreadsheet();
    $worksheet = $spreadsheet->getActiveSheet();
    foreach ($title as $key => $value) {
        $worksheet->setCellValueByColumnAndRow($key+1, 1, $value);
    }

    $row = 2; //从第二行开始
    foreach ($data as $item) {
        $column = 1;
        foreach ($item as $value) {
            $worksheet->setCellValueByColumnAndRow($column, $row, $value);
            $column++;
        }
        $row++;
    }
    $fileName = date('YmdHis');
    $fileType = 'Xlsx';
	excelBrowserExport($fileName, $fileType);
    $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');//按照指定格式生成Excel文件
    /*return */$writer->save('php://output');
}

/*
*导入
*/
function import()
{
    $info = Session::get('admin');
    $info = json_decode($info,TRUE);
    $file_size = $_FILES['file']['size'];
    if ($file_size > 5 * 1024 * 1024) {
        $this->error('文件大小不能超过5M');
        exit();
    }

    //限制上传表格类型
    $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
    //application/vnd.ms-excel  为xls文件类型
    if ($fileExtendName != 'xlsx') {
        $this->error('必须为excel表格,且必须为xlsx格式!');
        exit();
    }

    if (is_uploaded_file($_FILES['file']['tmp_name'])) {
        // 有Xls和Xlsx格式两种
        $objReader = IOFactory::createReader('Xlsx');

        $filename = $_FILES['file']['tmp_name'];
        $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格,或者是指定的表格
        $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
        $highestRow = $sheet->getHighestRow();       // 取得总行数
        $highestColumn = $sheet->getHighestColumn();   // 取得总列数
        //循环读取excel表格,整合成数组。如果是不指定key的二维,就用$data[i][j]表示。
        $pinyin = new Pinyin();
        Db::startTrans();
        try {
            for ($j = 2; $j <= $highestRow; $j++)
            {
                $data[$j - 2] = [
                    'id' => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue(),//这一个为参考,多字段可以按照这个继续添加即可
                ];
                if (empty($data[$j - 2]['id']))
                {
                    throw new \Exception('id不能为空!');
                }
                $result = Db::name('order')->save($data[$j - 2]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            $this->error($e->getMessage(), url('index'));
        }
        if ($result == true) {
            $this->success('导入成功!', url('index'));
        }
    }
}
/*
*公共
*/
function excelBrowserExport($fileName, $fileType)
{
    //ob_end_clean();
    //文件名称校验
    if (!$fileName) {
        trigger_error('文件名不能为空', E_USER_ERROR);
    }

    //Excel文件类型校验
    $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
    if (!in_array($fileType, $type)) {
        trigger_error('未知文件类型', E_USER_ERROR);
    }
    header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
    if ($fileType == 'Excel2007' || $fileType == 'Xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
    } else {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');
        header('Cache-Control: max-age=0');
    }
}

亲测链接
https://blog.csdn.net/qq_41851315/article/details/103051139
相关链接
https://blog.csdn.net/DestinyLordC/article/details/84071456
镜像安装
http://www.querylist.cc/docs/guide/v4/installation
https://php.cnpkg.org

==原本在windows下测试好好的上传到服务器之后导出订单就显示 网页可能暂时无法连接,或者它已永久性地移动到了新网址
我遇到这种情况是因为自己的php缺少了php7.2-xmlwrite拓展和php7.2-zip这个两个拓展 安装之后就可以使用了 ==

php -m
sudu apt-get install php7.2-xmlwrite
sudu apt-get install php7.2-zip

https://blog.csdn.net/m0_37962554/article/details/81060691

你可能感兴趣的:(学习,PHP,环境)