一、介绍
PhpSpreadsheet 是一个用纯 PHP 编写的库,它提供了一组类,允许您读取和写入各种电子表格文件格式,例如 Excel 和 LibreOffice Calc。
PhpSpreadsheet 是 PHPExcel 的下一个版本。它打破了兼容性,显著提升了代码库质量(命名空间、PSR 合规性、最新 PHP 语言特性的使用等)。
由于所有工作已转移到 PhpSpreadsheet,PHPExcel 将不再维护。所有针对 PHPExcel 的贡献,无论是补丁还是新功能,都应以 PhpSpreadsheetmaster分支为目标。
github 地址:
https://github.com/phpoffice/phpspreadsheet
二、安装
composer 安装:
composer require phpoffice/phpspreadsheet
三、使用
导出:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$activeWorksheet = $spreadsheet->getActiveSheet();
$activeWorksheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
导入:
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if($ext == 'xlsx'){
    $reader = new Xlsx();
}else{
    $reader = new Xls();
}
try{
    $spreadsheet = $reader->load($fileLocal);
}catch(\PhpOffice\PhpSpreadsheet\Reader\Exception $e){
    die($e->getMessage());
}
$sheet = $spreadsheet->getActiveSheet();
$list = [];
$listEn = [];
foreach ($sheet->getRowIterator() as $row){
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false); //这个循环将访问所有单元格,包括空白的。
    $listTmp = [];
    $listEnTmp = [];
    foreach ($cellIterator as $cell){
        if(!is_null($cell)){
            try{
                $column = $cell->getColumn();
            }catch (\PhpOffice\PhpSpreadsheet\Exception $e){
                return addError($e->getMessage());
            }
            try{
                $row = $cell->getRow();
            }catch(\PhpOffice\PhpSpreadsheet\Exception $e){
                return addError($e->getMessage());
            }
            $value = $cell->getValue();
            $listTmp[] = $value;
            $listEnTmp[$column.$row] = $value;
        }
    }
    $list[] = $listTmp;
    $listEn[] = $listEnTmp;
} PHP扩展 第10章 导入导出excel
                        PHP扩展 第10章 导入导出excel
                    