使用 PhpSpreadsheet 將 Excel 表格數據導入到數據庫

1、安裝 PhpSpreadsheet
composer require phpoffice/phpspreadsheet
2、控制器代碼
public function importExcel()
{
    // 接收文件
    $file = $_FILES['file']['tmp_name'];
    // 創建讀操作
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
    // 打開文件、載入excel表格
    $spreadsheet = $reader->load($file);
    // 獲取活動工作薄
    $sheet = $spreadsheet->getActiveSheet();

   
    // 獲取總行數
    $highestRow = $sheet->getHighestRow();
    
    // 存放插入成功的記錄
    $successLog = [];
    // 存放插入失敗的記錄
    $failLog = [];

    // 從第二行開始讀取表格數據,循環寫入數據庫
    for ($i = 2; $i <= $highestRow; $i++) {
        // 第 1 次循環獲取第 3 列 第 2 行單元格的值,第 2 次循環獲取第 3 列 第 3 行單元格的值
        $name = $sheet->getCellByColumnAndRow(3,$i)->getValue();
        $age = $sheet->getCellByColumnAndRow(4,$i)->getValue();
        $sex = $sheet->getCellByColumnAndRow(5,$i)->getValue();
        $room = $sheet->getCellByColumnAndRow(6,$i)->getValue();
        // 假設數據表有以下字段
        $data = [
            'name' => $name,
            'age' => $age,
            'sex' => $sex,
            'room_id' => $room,
            'create_time' => date('Y-m-d H:i:s', time())
        ];
        $insert = Db::name('student')->insert($data);
        if ($insert) {
            $successLog[] = '第'.$i.'條,插入成功';
        } else {
            $failLog[] = '第'.$i.'條,插入失敗';
        }
    }
    // 將成功數和失敗數返回給 ajax
    return json(['success' => count($successLog), 'fail' => count($failLog)]);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章