스프레드시트에서 데이터베이스로
PHP에서 Excel 파일을 MySQL 데이터베이스로 가져 오는 방법에 대한 단계별 자습서를 시작합니다. 스프레드 시트에서 일부 데이터를 읽고 데이터베이스에 저장 해야 하는 프로젝트가 있습니까?
안타깝게도 PHP는 기본적으로 Excel 파일을 읽을 수 없습니다. 따라서 Excel 파일을 데이터베이스로 가져 오려면 다음을 수행하십시오.
그러나 우리는 어떻게 마술을 합니까? 이 안내서는 실제 예제를 통해 정확한 단계를 안내합니다. 계속 읽으십시오!
ⓘ이 튜토리얼을 시작할 때 모든 예제 소스 코드가 포함 된 zip 파일을 포함 시켰으므로 모든 내용을 복사하여 붙여 넣을 필요가 없습니다.
다운로드
먼저 약속 한대로 소스 코드에 대한 다운로드 링크가 있습니다.
소스 코드 다운로드
소스 코드를 다운로드하려면 여기를 클릭하십시오. MIT 라이센스에 따라 릴리스되었으므로 그 위에 빌드하거나 자신의 프로젝트에서 자유롭게 사용하십시오.
빠른 시작
DUMMY 데이터베이스 및 엑셀
가져 오기 스크립트를 시작하기 전에 이 안내서의 예제로 사용할 더미 데이터베이스 및 Excel 파일이 있습니다.
DUMMY 테이블
CREATE TABLE `test` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `test` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `email` (`email`); ALTER TABLE `test` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
3 개의 필드만 있는 매우 간단한 테스트 테이블.
Field | Description |
id | Primary key, auto-increment. |
name | User name. |
User email address, unique. |
DUMMY EXCEL 파일
다음으로 업로드에 사용될 더미 데이터가 Excel 파일에 있습니다.
Name | |
John Doe | john@doe.com |
Jane Doe | jane@doe.com |
Josh Doe | josh@doe.com |
Joy Doe | joy@doe.com |
Janus Doe | janus@doe.com |
Jay Doe | jay@doe.com |
June Doe | june@doe.com |
Julius Doe | julius@doe.com |
Jess Doe | jess@doe.com |
Jack Doe | jack@doe.com |
업로드 양식
이제 업로드 할 더미 데이터베이스 테이블과 Excel 파일을 설정 했으므로 간단한 HTML 업로드 양식을 작성해 보겠습니다.
스크립트
<html> <head> <title> Simple File Uploader </title> </head> <body> <form action="3-import.php" method="post" enctype="multipart/form-data"> <p> Choose an Excel file: </p> <input type="file" name="upexcel" accept=".csv,.xls,.xlsx" required/> <input type="submit" value="Upload"/> </form> </body> </html>
설명
그렇습니다.이 스크립트에는 특별한 것이 없습니다. 진정한 블루 HTML 파일 업로드 양식 –이 파일을 예쁘게 만들거나 파일 업로드 플러그인을 구현하십시오. 한 가지 주의 할 점 – 업로드 파일 유형 제한 accept = ". csv, .xls, .xlsx"는 이전 브라우저에서 작동하지 않습니다. 따라서 나중에 서버 측에서 파일 검사를 수행해야 합니다.
PHPSPREADSHEET 설치
계속해서 PHP는 기본적으로 Excel 파일을 읽을 수 없습니다. 따라서 타사 라이브러리 호출 PHP SpreadSheet를 다운로드하여 사용해야 합니다.
라이브러리 얻기
Composer – Git과 같은 애플리케이션을 다운로드하여 설치하십시오. 라이브러리를 자동으로 가져 오는 데 매우 유용합니다. 그런 다음 명령 프롬프트 (또는 터미널)에서 프로젝트 폴더로 이동하고 composer require phpoffice / phpspreadsheet를 실행하십시오.
D:\http\test>composer require phpoffice/phpspreadsheet Using version ^1.6 for phpoffice/phpspreadsheet ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 4 installs, 0 updates, 0 removals - Installing markbaker/matrix (1.1.4): Loading from cache - Installing markbaker/complex (1.4.7): Loading from cache - Installing psr/simple-cache (1.0.1): Loading from cache - Installing phpoffice/phpspreadsheet (1.6.0): Loading from cache phpoffice/phpspreadsheet suggests installing mpdf/mpdf (Option for rendering PDF with PDF Writer) phpoffice/phpspreadsheet suggests installing dompdf/dompdf (Option for rendering PDF with PDF Writer) phpoffice/phpspreadsheet suggests installing tecnickcom/tcpdf (Option for rendering PDF with PDF Writer) phpoffice/phpspreadsheet suggests installing jpgraph/jpgraph (Option for rendering charts, or including charts with PDF or HTML Writers) Writing lock file Generating autoload files
IMPORT HANDLER
마지막으로 PHP SpreadSheet를 사용하여 업로드 된 파일을 읽고 데이터베이스로 데이터를 가져 오기만 하면 됩니다.
THE IMPORT SCRIPT
// (0) CONFIG // MUTE NOTICES error_reporting(E_ALL & ~E_NOTICE); // DATABASE SETTINGS // ! CHANGE THESE TO YOUR OWN ! define('DB_HOST', 'localhost'); define('DB_NAME', 'test'); define('DB_CHARSET', 'utf8'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); // (1) FILE CHECK // * HTML file type restriction can still miss at times // @TODO - Add more of your own file checks if you want. // E.g. Restrict upload size to prevent resource hogging. if (!isset($_FILES['upexcel']['tmp_name']) || !in_array($_FILES['upexcel']['type'], [ 'text/x-comma-separated-values', 'text/comma-separated-values', 'text/x-csv', 'text/csv', 'text/plain', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ])) { die("Invalid file type"); } // (2) INIT MYSQL // ATTEMPT CONNECT try { $str = "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET; if (defined('DB_NAME')) { $str .= ";dbname=" . DB_NAME; } $pdo = new PDO( $str, DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false ] ); } // ERROR catch (Exception $ex) { die("Failed to connect to database"); } // (3) INIT PHP SPREADSHEET require 'vendor/autoload.php'; if (pathinfo($_FILES['upexcel']['name'], PATHINFO_EXTENSION) == 'csv') { $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); } else { $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); } $spreadsheet = $reader->load($_FILES['upexcel']['tmp_name']); // (4) READ DATA & IMPORT // ! NOTE ! EXCEL MUST BE IN EXACT FORMAT! // @TODO - Add your own data validation checks if you want. // @TODO - Output a nicer HTML import result if you want. $worksheet = $spreadsheet->getActiveSheet(); $sql = "INSERT INTO `test` (`name`, `email`) VALUES (?, ?)"; foreach ($worksheet->getRowIterator() as $row) { // Fetch data $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); $data = []; foreach ($cellIterator as $cell) { $data[] = $cell->getValue(); } // Insert database print_r($data); try { $stmt = $pdo->prepare($sql); $stmt->execute($data); // $this->pdo->lastInsertId(); // If you need the last insert ID echo "OK<br>"; } catch (Exception $ex) { echo "ERROR<br>"; } $stmt = null; } // (5) CLOSE DATABASE CONNECTION if ($stmt !== null) { $stmt = null; } if ($pdo !== null) { $pdo = null; }
설명
이것은 심각한 뇌 손상을 일으킬 수 있는 일부 스크립트처럼 보입니다. 그러나 코드를 섹션별로 살펴보면 실제로 매우 간단합니다.
그러나 이것은 작동하는 골격 코드 일 뿐이며 여전히 많은 작업이 필요합니다.
유용한 비트
이것이 이 프로젝트의 전부이며, 여기에 도움이 될만한 추가 정보에 대한 작은 섹션이 있습니다.
참조 및 링크
등록된 댓글이 없습니다.