EasySwoole+phpspreadsheet进行Excel的导入导出

首先,使用composer引入phpspreadsheet,composer requierd。这个就不细讲,本章主要是介绍如何使用phpspreadsheet进行项目中的导入导出。

导入:

<?php
use \PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use \PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class Excel{
    public function import($file){
         $objRead = IOFactory::createReader('Xlsx');
         if ( ! $objRead->canRead($file)) {
            $objRead = IOFactory::createReader('Xls');
            if ( ! $objRead->canRead($file)) {
                return false;
            }
        }
        //设置为只读
        $objRead->setReadDataOnly(true);
        $obj       = $objRead->load($file);
        $currSheet = $obj->getSheet($sheet);
        /* 取得最大行列号 */
        $columnH = $currSheet->getHighestColumn();
        $columnCnt = Coordinate::columnIndexFromString($columnH);
        //列号可以自定义
        $columnCnt = 1;表示只获取一列
        $rowCnt = $currSheet->getHighestRow();
        $data   = [];
        //第一行为标题,所以从第二行开始读取
        for ($row = 2;$row <= $rowCnt;$row++) {
            for ($col = 1;$col <= $columnCnt;$col++) {
                $cellName = Coordinate::stringFromColumnIndex($col);
                //获取定位,拼接
                $cellId = $cellName . $row;
                $value  = $currSheet->getCell($cellId)->getValue();
                if ( ! empty($value)) {
                    //我这里因为只获取一列的数据,所以只用了一维数组
                    $data[] = trim($currSheet->getCell($cellId)->getValue());
                }
            }
        }
        return $data;
    }
}

导出:

public function download($AResult){
    $spreadsheet = new Spreadsheet();
    $sheet       = $spreadsheet->getActiveSheet();
    //设置第一行的表头
    $sheet->setCellValue('A1', '我是第一行');
    //把数据循环写入到excel里
    foreach ($AResult as $k => $v) {
        $num = $k + 2;
        //从第二行开始写
        $sheet->setCellValue('A' . $num, $v);
    }
    $writer   = new Xlsx($spreadsheet);
    //这里可以写绝对路径,其他框架到这步就结束了
    $writer->save('test.xlsx');
    //关闭连接,销毁变量
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
}
public function swooleOut(){
    //因为swoole有自己的response,header头不允许直接设置,其他框架可以直接用上一个函数
    $this->download($AResult);
    //生成文件后,使用response输出
        $this->response()->write(file_get_contents('test.xls'));
        $this->response()->withHeader('Content-type', 'application/' . $type);
        $this->response()->withHeader('Content-Disposition', 'attachment;filename="test.xls"');
        $this->response()->withHeader('Cache-Control','max-age=0');
        $this->response()->end();
}

打赏作者

《EasySwoole+phpspreadsheet进行Excel的导入导出》上有3条评论

  1. 导出根本用不了呀,
    $writer = new Xlsx($spreadsheet);
    //这里可以写绝对路径,其他框架到这步就结束了
    $writer->save(‘test.xlsx’);
    save方法都不存在

发表评论

电子邮件地址不会被公开。