Đọc dữ liệu Excel import MySQL

Để đọc dữ liệu excel ta dùng thư viện mã nguồn mở PHPEXCEL. Bạn có thể tải về từ trang GitHub 

Tuy nhiên cần lưu ý: theo document gửi kèm thì thư viện chỉ hoạt động khi:

  • Dùng cho php 5.2.0 trở lên
  • Phải thiết enable các component gồm php_zip; php_xml; php_gp2  trong php.ini

 

Ví dụ dưới đây với bối cảnh có một file Excel gồm 3 field id, firstname, lastname

Đoạn trình sẽ đọc dữ liệu vào và update vào một table đã có sẵn gồm 3 field ID (tự động điền), FirstName, LastName của csdl MySQL đã được test thực tế.

 

<?php

//include các thông tin  và truy cập datatbase trên biến $db

require('./inc/config.php');

//  Include thư viện PHPExcel_IOFactory vào

include 'Classes/PHPExcel/IOFactory.php';

if (isset($_POST['submit'])) {

          $inputFileName=$_FILES['file']['tmp_name'];

 

//  Tiến hành đọc file excel

try {

    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);

    $objReader = PHPExcel_IOFactory::createReader($inputFileType);

    $objPHPExcel = $objReader->load($inputFileName);

} catch(Exception $e) {

    die('Lỗi không thể đọc file "'.pathinfo($inputFileName,PATHjoomla_BASENAME).'" : '.$e->getMessage());

}

 

// Lấy sheet đầu tiên

$sheet = $objPHPExcel->getSheet('0');

 

// Lấy tổng số dòng của file,

$highestRow = $sheet->getHighestRow();

 

// Lấy tổng số cột của file, nếu cần thiết

//$highestColumn = $sheet->getHighestColumn();

 

//  Thực hiện việc lặp qua từng dòng của file, để lấy thông tin

for ($row = 2; $row <= $highestRow; $row++){

    $firstname=$sheet->getCellByColumnAndRow(1,$row)->getValue();

    $lastname=$sheet->getCellByColumnAndRow(2,$row)->getValue();

    $sql="insert into myuser(firstname,lastname) values ('$firstname','$lastname')";

    $db->query($sql);

    //vấn đề còn tồn đọng là unicode

}//for

//if isset

?>

<!DOCTYPE html>

<html>

<head>

          <title>Import Data</title>

</head>

<body>

          <form method="post" enctype="multipart/form-data">

                     <input type="file" name="file">

                     <input type="submit" name="submit" value="OK">

          </form>

</body>

</html>