1. 安装:
    composer require phpoffice/phpspreadsheet
  2. 导出:
    <?php
    // 1. 引入包
    require_once 'vendor/autoload.php';
    // 2. 使用命名空间
    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx as Writer;
    // 3. 实例化类
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    // 4. 构造标题
    $title = array(
     array(
         'id',
         'name',
         'weight'
     )
    );
    // 5. 构造内容
    $content = array(
     array(
         '1',
         'name_a',
         '50kg'
     ),
     array(
         '2',
         'name_b',
         '60kg'
     ),
     array(
         '3',
         'name_c',
         '70kg'
     )
    );
    // 6. 合并标题/内容
    $data = array_merge($title,$content);
    $sheet->fromArray($data);
    // 7. 实例化写入类
    $writer = new Writer($spreadsheet);
    // 8. 保存到文件
    $writer->save('test.xlsx');
  3. 导入:
    <?php
    // 1. 引入包
    require_once 'vendor/autoload.php';
    // 2. 使用命名空间
    use PhpOffice\PhpSpreadsheet\Reader\Xlsx as Reader;
    use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
    // 3. 实例化读取类
    $reader = new Reader();
    // 4. 只读取数据
    $reader->setReadDataOnly(true);
    // 5. 加载文件
    $obj = $reader->load('test.xlsx');
    // 6. 设置当前活动工作表
    $current_sheet = $obj->getSheet(0);
    // 7. 获取最大列
    $column_high = $current_sheet->getHighestColumn();
    $column_count = Coordinate::columnIndexFromString($column_high);
    // 8. 获取最大行
    $row_count = $current_sheet->getHighestRow();
    // 9. 定义数据
    $data = [];
    // 10. 构造数据
    for ($row = 1; $row <= $row_count; $row++) {
     $is_null = true;
     for ($column = 1; $column <= $column_count; $column++) {
         $cell_name = Coordinate::stringFromColumnIndex($column);
         $cell_id = $cell_name . $row;
         $data[$row - 1][$column - 1] = trim($current_sheet->getCell($cell_id)->getFormattedValue());
         if (!empty($data[$row - 1][$column - 1])) {
             $is_null = false;
         }
     }
     if ($is_null) {
         unset($data[$row - 1]);
     }
    }
    // 11. 输出
    var_dump($data);
文档更新时间: 2020-08-08 20:40   作者:lee