본문 바로가기
웹 개발 이야기/php

[PHP] Excel data upload

by Gommin 2023. 3. 16.

// 그누보드 기반으로 제작되었다.
// 여기저기 검색하면서 오타들이 남발하는 자료들에 허덕이다 이것저것 섞어서 수정함
// form으로 excel 파일을 첨부한 후 post 방식으로 처리했다.

include '../lib/phpexcel_1_8/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
include "../lib/phpexcel_1_8/Classes/PHPExcel/IOFactory.php";

$allData = array();
$excelfile = $_FILES['excelfile']['tmp_name'];
$objReader = PHPExcel_IOFactory::load($excelfile);
$sheetsCount = $objReader -> getSheetCount();
$objReader -> setActiveSheetIndex(0);

for($i = 0; $i < $sheetsCount; $i++) {
    $sheet = $objReader -> getActiveSheet();
    $rowIterator = $sheet->getRowIterator();
    $highestColumn = $sheet -> getHighestColumn(); // 마지막 컬럼

    foreach ($rowIterator as $row) { // 모든 행에 대해서
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false);
    }

    $maxRow = $sheet->getHighestRow(); // 마지막 행

    for ($i = 0 ; $i <= $maxRow ; $i++) {
        if($i>0){
            $ele1 = $sheet->getCell('A' . $i)->getValue(); // A열
            $ele2 = $sheet->getCell('B' . $i)->getValue(); // B열
            $ele3 = $sheet->getCell('C' . $i)->getValue(); // C열
            $ele4 = $sheet->getCell('D' . $i)->getValue(); // D열
            $ele5 = $sheet->getCell('E' . $i)->getValue(); // E열
            $ele6 = $sheet->getCell('F' . $i)->getValue(); // F열
            //echo $ele1." | ".$ele2." | ".$ele3." | ".$ele4." | ".$ele5." | ".$ele6."<br>";

            $sql2 = "select * from g5_lecture_q where l_idx = '{$l_idx}' ";
            $row2 = sql_fetch($sql2);
            if($row2['idx']){
                $sql3 = "update g5_lecture_q set ";
                $sql3 = "l_idx = '{$l_idx}', ";
                $sql3 = "ca_idx1 = '{$ca_idx1}', ";
                $sql3 = "ca_idx2 = '{$ca_idx2}', ";
                $sql3 = "l_question = '{$ele1}', ";
                $sql3 = "l_answer1 = '{$ele2}', ";
                $sql3 = "l_answer2 = '{$ele3}', ";
                $sql3 = "l_answer3 = '{$ele4}', ";
                $sql3 = "l_answer4 = '{$ele5}', ";
                $sql3 = "answer_correct = '{$ele6}' ";
                $sql3 = "where idx = '{$row2['idx']}' ";
                sql_query($sql3);
            }else{
                $sql3 = "insert into g5_lecture_q set ";
                $sql3 = "l_idx = '{$l_idx}', ";
                $sql3 = "ca_idx1 = '{$ca_idx1}', ";
                $sql3 = "ca_idx2 = '{$ca_idx2}', ";
                $sql3 = "l_question = '{$ele1}', ";
                $sql3 = "l_answer1 = '{$ele2}', ";
                $sql3 = "l_answer2 = '{$ele3}', ";
                $sql3 = "l_answer3 = '{$ele4}', ";
                $sql3 = "l_answer4 = '{$ele5}', ";
                $sql3 = "answer_correct = '{$ele6}' ";
                sql_query($sql3);
            }
        }
    }
}

echo '<script>alert("문제가 등록되었습니다."); window.opener.location.reload(); window.close();</script>';



댓글