Php data import from excel

I want to import data from excel file using PHP and then if possible, save it to a MySQL database.

morten.c's user avatar

morten.c

3,4125 gold badges40 silver badges45 bronze badges

asked Jan 14, 2010 at 19:32

air's user avatar

Importing from Excel files (XLS) is way harder than improting from CSV files. Usually I save my XLS to CSV with Excel then work on this CSV with PHP…

Look at PHP function fgetcsv at:
http://ca.php.net/manual/en/function.fgetcsv.php

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />n";
        }
    }
    fclose($handle);
}
?> 

If you still want to load XLS directly from PHP it’s possible (but how reliable)… A quick seach resulted in http://sourceforge.net/projects/phpexcelreader/ which might be helpful.

answered Jan 14, 2010 at 19:34

AlexV's user avatar

AlexVAlexV

22.5k17 gold badges87 silver badges122 bronze badges

1

Quite possible. You can save your Excel file as a CSV file, and use fgetcsv() to read that file in to PHP. fgetcsv() will parse your data into an array, which you can then create SQL queries out of to put into your database.

If all you’re doing is putting it into a database, you might be able to bypass the need for a PHP script entirely and just use MySQL’s LOAD DATA INFILE syntax on your CSV file instead:

LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY 'n'
(field1, filed2, field3);

answered Jan 14, 2010 at 19:36

zombat's user avatar

zombatzombat

92.1k24 gold badges157 silver badges164 bronze badges

Best bet is to export from Excel to a CSV (Comma separated values) file. These files are easy to parse and load. If you are reading directly from an XLS file, I’m not sure how to do that. You might want to look and see if there is a libarary for PHP that can read Excel data files.

answered Jan 14, 2010 at 19:34

FrustratedWithFormsDesigner's user avatar

Here’s a tutorial on reading/writing an Excel spreadsheet directly (without having to export to CSV). The necessary packages are available from SourceForge and PEAR (cf. article).

answered Jan 14, 2010 at 19:42

AndiDog's user avatar

AndiDogAndiDog

68k21 gold badges160 silver badges204 bronze badges

<?
 i$db = mysql_connect(“localhost”, “root”, “”) or die(“Could not connect.”);

if(!$db)

die(“no db”);

if(!mysql_select_db(“test”,$db))

die(“No database selected.”);

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

{

$filename=$_POST['filename'];

$handle = fopen(“$filename”, “r”);

while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE)

{

$import=”INSERT into sample(name,email) values(‘$data[0]‘,’$data[1]‘)”;

mysql_query($import) or die(mysql_error());

}

fclose($handle);

print “Import done”;

}

else

{

print “<form action=’import.php’ method=’post’>”;

print “Type file name to import:<br>”;

print “<input type=’text’ name=’filename’ size=’20′><br>”;

print “<input type=’submit’ name=’submit’ value=’submit’></form>”;

}
 ?>

Source

Matthieu's user avatar

Matthieu

4,5854 gold badges40 silver badges59 bronze badges

answered Jan 21, 2011 at 11:18

Ashwani Singh's user avatar

In this article, you will learn how to import Excel data into the MySQL database using the PHPExcel library. PHPExcel is a library written in pure PHP and provides a set of classes that allow you to write to and read from different spreadsheet file formats.

The web applications may contain data in various formats or they may have to collect data from various sources. It is not necessary that all the gathered data be compatible for storage on the server. Most large-scale websites use server-side code to dynamically display different data when needed. A database stores information more efficiently and can handle volumes of information that would be unmanageable in a spreadsheet. Spreadsheets have record limitations, whereas a database does not. So, we need to store this data in a database for future use. Here, we are using the PHPExcel library to import a CSV file into a PHP database. You can easily implement this by following these steps.

These are the steps to import Excel data to MySQL using PHPExcel-

Install PHPExcel with Composer

First, we need to install the PHPExcel library to read excel data. You can either download this from Github or install it using Composer. If your system does not have composer installed, then first download the latest composer version from its official website-

https://getcomposer.org/download/

You can check a successful installation using the following command on cmd

Install Composer

Now, go to your project directory on the command prompt and run the following command to install the PHPExcel library.

E:wampwwwexceltomysql>composer require phpoffice/phpexcel

After this, you will notice that Composer has downloaded all libraries under the ‘vendor‘ directory of your project root. Here is the file structure of this project-

PHPExcel file Structure

Excel File

Suppose we have the following excel file containing school program participants data-

PHPExcel file Structure

Database Script (db.php)

Here, we have written the database connection code. Make sure to replace ‘hostname‘, ‘username‘, ‘password‘ and ‘database‘ with your database credentials and name.

<?php
	$hostname = "localhost";
	$db = "school";
	$password = "";
	$user = "root";
	$mysqli = new mysqli($hostname, $user, $password, $db);
?>

If we want to store or import Excel data into the MySQL database, we need a database table. So, we have a MySQL database ‘school‘ and in it we have to create a ‘participants‘ table with the given columns.

CREATE TABLE IF NOT EXISTS `participants` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `rollno` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `program` varchar(100) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

Create Upload File Template

To create a file uploader, we have created a simple HTML file upload form ‘index.php‘. If a form contains any file type input field, then we have to add an attribute ‘encrypt‘ with a value of ‘multipart/form-data‘.

<!DOCTYPE html>
<html>
<head>
	<title>PHP import Excel data</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1>Upload Excel File</h1>
	<form method="POST" action="uploadexcel.php" enctype="multipart/form-data">
		<div class="form-group">
			<label>Choose File</label>
			<input type="file" name="uploadFile" class="form-control" />
		</div>
		<div class="form-group">
			<button type="submit" name="submit" class="btn btn-success">Upload</button>
		</div>
	</form>
</div>
</body>
</html>

Parse Excel and Insert into Database (uploadexcel.php)

In this PHP code, we have validated the uploaded file type and then included the PHPExcel library files and database configuration file (db.php). We have validated the execution of each logical code. It returns an error message on failure. Further, PHPExcel parses the excel file, reads the data, and stores it in an array. We have looped over this array to insert data into the database and show the response to the web browser.

<?php  

if(isset($_POST['submit'])) {
     if(isset($_FILES['uploadFile']['name']) && $_FILES['uploadFile']['name'] != "") {
        $allowedExtensions = array("xls","xlsx");
        $ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
		
        if(in_array($ext, $allowedExtensions)) {
				// Uploaded file
               $file = "uploads/".$_FILES['uploadFile']['name'];
               $isUploaded = copy($_FILES['uploadFile']['tmp_name'], $file);
			   // check uploaded file
               if($isUploaded) {
					// Include PHPExcel files and database configuration file
                    include("db.php");
					require_once __DIR__ . '/vendor/autoload.php';
                    include(__DIR__ .'/vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php');
                    try {
                        // load uploaded file
                        $objPHPExcel = PHPExcel_IOFactory::load($file);
                    } catch (Exception $e) {
                         die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
                    }
                    
                    // Specify the excel sheet index
                    $sheet = $objPHPExcel->getSheet(0);
                    $total_rows = $sheet->getHighestRow();
					$highestColumn      = $sheet->getHighestColumn();	
					$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);		
					
					//	loop over the rows
					for ($row = 1; $row <= $total_rows; ++ $row) {
						for ($col = 0; $col < $highestColumnIndex; ++ $col) {
							$cell = $sheet->getCellByColumnAndRow($col, $row);
							$val = $cell->getValue();
							$records[$row][$col] = $val;
						}
					}
					$html="<table border='1'>";
					$html.="<tr><th>Roll No</th>";
					$html.="<th>Name</th><th>Age</th>";
					$html.="<th>Program</th></tr>";
					foreach($records as $row){
						// HTML content to render on webpage
						$html.="<tr>";
						$rollno = isset($row[0]) ? $row[0] : '';
						$name = isset($row[1]) ? $row[1] : '';
						$age = isset($row[2]) ? $row[2] : '';
						$program = isset($row[3]) ? $row[3] : '';
						$html.="<td>".$rollno."</td>";
						$html.="<td>".$name."</td>";
						$html.="<td>".$age."</td>";
						$html.="<td>".$program."</td>";
						$html.="</tr>";
						// Insert into database
						$query = "INSERT INTO participants (rollno,name,age,program) 
								values('".$rollno."','".$name."','".$age."','".$program."')";
						$mysqli->query($query);		
					}
					$html.="</table>";
					echo $html;
					echo "<br/>Data inserted in Database";
				
                    unlink($file);
                } else {
                    echo '<span class="msg">File not uploaded!</span>';
                }
        } else {
            echo '<span class="msg">Please upload excel sheet.</span>';
        }
    } else {
        echo '<span class="msg">Please upload excel file.</span>';
    }
}
?>

On successful execution, the data will be inserted in the database as in the given screenshot-

Excel store in database

Related Articles


PHP capitalize first letter
Age calculator in PHP
PHP Display PDF file from Database
Remove empty values from array PHP

Remove duplicates from array PHP

Floor function in PHP

Convert stdclass object to array PHP
How to read CSV file in PHP and store in MySQL
Generating word documents with PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Simple PHP email form
Password reset system in PHP
HTTP authentication with PHP
PHP file cache library
PHP get current directory url
How to prevent CSRF attack in PHP
Forgot Password Script PHP mysqli database
PHP Contact Form with Google reCAPTCHA
HTML Form Validation in PHP

PHP sanitize input for MySQL
Simple pagination in PHP with MySQL
Store Emoji character in MySQL using PHP

by Vincy. Last modified on April 8th, 2023.

Database backup and restore is the most important part of maintaining software. Taking automatic periodical backup is a must for any project.

In case of unknown security flaws which may collapse your system. In such an unfortunate situation, it will be the holy grail to save you if you have a backup.

It is not only enough to take a backup by exporting your database. Also, we need to experiment with importing backups to ensure the restoration.

Backup files can be in any format. Many of the database clients support SQL, Excel or CSV format files to import external data.

We will create our own PHP database client only for importing Excel data into a database.

Restoring Excel backup into a database via programming will save us time. Let us study how to implement a quick restore by importing bulk data from Excel files. You may visit my earlier export data in CSV format if you want an export example.

This screenshot shows the output by displaying the list of imported rows from the database.

import excel to mysql output

What is inside?

  1. About this Excel import example
  2. File Structure
  3. Database script
  4. Creating UI to upload import template
  5. Parse Excel data using PHPSpreadsheet
  6. Output: Excel import and data listing

About this Excel import example

This example allows users to choose the import template via HTML form input. A sample Excel template is added with this downloadable resource.

With a valid file, the HTML form submitted will call PHP to process Excel parsing.

In PHP, the PHPSpreadsheet library is used to read the Excel file data and convert it into an array.

The code will execute the database insert row by row by iterating the array data.

File Structure

See the Excel import example’s file structure shown below. The vendor folder has the PHPSpreadsheet library and its dependencies.

I have given a sample import template with these files to experiment with the import operation.

The schema.sql has the script to create the target database. You can find the SQL script in the next section.

Import Excel File Structure

Database script

Import the following SQL script and create a database environment. Also, configure your database details in DataSource.php to make this example work.

--
-- Database: `import_excel`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_info`
--

CREATE TABLE `tbl_info` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `description` varchar(50) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

--
-- Indexes for table `tbl_info`
--
ALTER TABLE `tbl_info`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `tbl_info`
--
ALTER TABLE `tbl_info`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;;

Creating UI to upload import template

This HTML form with the file upload option is used to choose the Excel source. On submitting this form, the Excel file will be sent to the PHP to parse the data source. This file upload option will only allow the Excel files to choose using the accept attribute.

This code also contains the response HTML for displaying the message returned from PHP. This message is shown based on the type of response sent from PHP after Excel import.

<h2>Import Excel File into MySQL Database using PHP</h2>

	<div class="outer-container">
		<div class="row">
			<form class="form-horizontal" action="" method="post"
				name="frmExcelImport" id="frmExcelImport"
				enctype="multipart/form-data" onsubmit="return validateFile()">
				<div Class="input-row">
					<label>Choose your file. <a href="Template/import-template.xlsx"
						download>Download excel template</a></label>
					<div>
						<input type="file" name="file" id="file" class="file"
							accept=".xls,.xlsx">
					</div>
					<div class="import">
						<button type="submit" id="submit" name="import" class="btn-submit">Import
							Excel and Save Data</button>
					</div>
				</div>
			</form>
		</div>
	</div>
	<div id="response"
		class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
<?php
$sqlSelect = "SELECT * FROM tbl_info";
$result = $db->select($sqlSelect);
if (! empty($result)) {
    ?>

    <table class='tutorial-table'>
		<thead>
			<tr>
				<th>Name</th>
				<th>Description</th>
			</tr>
		</thead>
<?php
    foreach ($result as $row) { // ($row = mysqli_fetch_array($result))
        ?>
        <tbody>
			<tr>
				<td><?php  echo $row['name']; ?></td>
				<td><?php  echo $row['description']; ?></td>
			</tr>
<?php
    }
    ?>
        </tbody>
	</table>
<?php
}
?>

Parse Excel data using PHPSpreadsheet

In this PHP code, I specified the array of allowed file types for the file-type validation in PHP. I validated the uploaded file type along with the array allowed type.

If a match is found, the code will execute other logic. Otherwise, it will return the error message to the user.

With successful validation, excel file parsing read and convert the data into an array. Each array index has an array of row data. After reading the non-empty row data, I ran the database insert and showed the response.

<?php
use PhppotDataSource;
use PhpOfficePhpSpreadsheetReaderXlsx;

require_once 'DataSource.php';
$db = new DataSource();
$conn = $db->getConnection();
require_once ('vendor/autoload.php');

if (isset($_POST["import"])) {

    $allowedFileType = [
        'application/vnd.ms-excel',
        'text/xls',
        'text/xlsx',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];

    if (in_array($_FILES["file"]["type"], $allowedFileType)) {

        $targetPath = 'uploads/' . $_FILES['file']['name'];
        move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);

        $Reader = new PhpOfficePhpSpreadsheetReaderXlsx();

        $spreadSheet = $Reader->load($targetPath);
        $excelSheet = $spreadSheet->getActiveSheet();
        $spreadSheetAry = $excelSheet->toArray();
        $sheetCount = count($spreadSheetAry);

        for ($i = 1; $i <= $sheetCount; $i ++) {
            $name = "";
            if (isset($spreadSheetAry[$i][0])) {
                $name = mysqli_real_escape_string($conn, $spreadSheetAry[$i][0]);
            }
            $description = "";
            if (isset($spreadSheetAry[$i][1])) {
                $description = mysqli_real_escape_string($conn, $spreadSheetAry[$i][1]);
            }

            if (! empty($name) || ! empty($description)) {
                $query = "insert into tbl_info(name,description) values(?,?)";
                $paramType = "ss";
                $paramArray = array(
                    $name,
                    $description
                );
                $insertId = $db->insert($query, $paramType, $paramArray);
                // $query = "insert into tbl_info(name,description) values('" . $name . "','" . $description . "')";
                // $result = mysqli_query($conn, $query);

                if (! empty($insertId)) {
                    $type = "success";
                    $message = "Excel Data Imported into the Database";
                } else {
                    $type = "error";
                    $message = "Problem in Importing Excel Data";
                }
            }
        }
    } else {
        $type = "error";
        $message = "Invalid File Type. Upload Excel File.";
    }
}
?>

Note: Download the PHPSpreadsheet and include it in the vendor directory.

Download

↑ Back to Top

Содержание

  1. Реализация быстрого импорта из Excel на PHP
  2. Что использовать в качестве инструмента?
  3. Наша боль, как разработчиков
  4. И тут нас отпустило.
  5. Полученные результаты производительности
  6. PHP import Excel data to MySQL using PHPExcel
  7. These are the steps to import Excel data to MySQL using PHPExcel-
  8. Install PHPExcel with Composer
  9. Excel File
  10. Database Script (db.php)
  11. Create Upload File Template
  12. Parse Excel and Insert into Database (uploadexcel.php)
  13. Import Excel File into MySQL Database using PHP
  14. What is inside?
  15. About this excel import example
  16. File Structure
  17. Database script
  18. Creating UI to upload import template
  19. Parse excel data using PHPSpreadsheet
  20. How to import data from Excel to List in PHP
  21. 1. EasyXLS on Windows using .NET Framework (COM+) with PHP
  22. 2. EasyXLS on Linux, Mac, Windows using Java with PHP
  23. EasyXLS on Windows using .NET Framework (COM+) with PHP
  24. Step 1: Download and install EasyXLS Excel Library for COM+
  25. Step 2: Verify if COM and .NET extension is enabled in PHP
  26. See also
  27. How to enable COM and .NET extension in PHP?
  28. Step 3: Verify if EasyXLS is registered
  29. See also
  30. How to verify if EasyXLS is registered?
  31. Step 4: Run PHP code that imports data from Excel to DataSet
  32. EasyXLS on Linux, Mac, Windows using Java with PHP
  33. Step 1: Download EasyXLS Excel Library for Java
  34. Step 2: Install PHP/Java Bridge
  35. Step 3: Setup EasyXLS library in Tomcat
  36. Step 4: Run PHP code that imports data from Excel to DataSet
  37. Заметки программиста

Реализация быстрого импорта из Excel на PHP

Что использовать в качестве инструмента?

В качестве базового стандарта, используемого при импорте адресных баз, мы взяли Microsoft Excel. Объясняется это просто:

  • это стандартный инструмент, которым на базовом уровне владеют 100% пользователей компьютеров. Более того, в бизнесе — это де-факто корпоративный стандарт и используется даже, если на рабочих компьютерах Mac или Linux.
  • Практически все CRM-, CMS-, облачные или десктопные системы имеют экспорт в Excel или CSV, который простым пересохранением приводится к формату XLS или XLSX.
  • Известно также, что “90% ошибок ПО сидит в полуметре от монитора”. Не в обиду будет сказано рядовым пользователям, но мы должны учитывать самый базовый уровень подготовки и тех. поддержке для объяснения достаточно сказать “Загрузите Excel-файл”, а не объяснять процедуру подготовки файла в нужном формате.

Проблему пользователей при импорте адресных баз сняли. Но тут возникает уже проблема непосредственно разработки.

Наша боль, как разработчиков

Excel — это не open-source разработка, а проприетарное решение. Формат данных, особенно в новых версиях после 2007 года (xlsx), нетривиален. На Печкине используется PHP, поэтому мы начали поиск библиотек, которые позволят нам решить данную задачу. Но тут столкнулись с проблемой, что целый ряд библиотек, не позволяют читать xlsx:

  • php-spreadsheetreader reads a variety of formats (.xls, .ods AND .csv)
  • PHP-ExcelReader (xls only)
  • PHP_Excel_Reader (xls only)
  • PHP_Excel_Reader2 (xls only)
  • XLS File Reader Коммерческая и xls only
  • SimpleXLSX Из описания способен читать xlsx, однако, автор ссылается только на xls
  • PHP Excel Explorer Коммерческая и xls only

Обратила на себя наше внимание библиотека PHPExcel. Ее мы использовали еще несколько лет назад в сервисе sms-рассылок SMS24X7.ru. Петя Соколов (Petr_Sokolov), наш талантливый разработчик, написал обертку для этой библиотеки, исправляющую ряд ее недостатков и багов.

Библиотека, безусловно, интересная и развитая. Но для Печкина ее использовать стало невозможно уже через пару лет, когда выросли и мы и наши клиенты — ее катастрофическая требовательность к ресурсам и огромное время парсинга файлов. Например, нередки случаи загрузки на сервис адресных баз > 100 000 строк со сложной структурой. А если файл уже 500 000 строк и “весит” больше 30Мб?

И тут нас отпустило.

В процессе поисков мы наткнулись на коммерческую библиотеку libxl, увидев результаты “кустарного benchmark” на Stackoverflow.

Библиотека написана на C++, а благодаря великолепному объектно-ориентированному расширению для PHP от Ilia Alshanetsky, легка в освоении и интеграции (например, переписать наше текущее решение с PHPExcel на LibXL заняло около 3 часов). Что очень классно, учитывая, что, к сожалению, документации от разработчика расширения нет и необходимо пользоваться расширением Reflection.

Процесс установки очень прост.

В результате компиляции вы получите файл excel.so в папке /usr/lib/php5/20090626/. Теперь достаточно создать файл /etc/php5/conf.d/excel.ini с содержимым.

Проверим установился ли модуль и перезагрузим веб-сервер.

В коде все тоже очень просто. Подгружаете файл и читаете необходимые ячейки. Например, вот так:

Полученные результаты производительности

Отсутствие потребности в оперативной памяти (в процессе загрузки файла и его чтения) приятно порадовало.

А вот и прирост скорости загрузки excel-файла и его чтения на различных размерах адресных баз.

Данные тесты проводились на xlsx-файлах с N подписчиками в один стоблец с email. Реальные же адресные базы еще больше и сложнее и преимущество в скорости и потреблении памяти выглядит еще значительнее.

Стоимость библиотеки 199$ за девелоперскую лицензию, но, поверьте, это того стоит. Безусловно рекомендуем всем, кто сталкивается с проблемой импорта Excel-файлов на свой сервис.

Источник

PHP import Excel data to MySQL using PHPExcel

In this article, you will learn how to import Excel data into the MySQL database using the PHPExcel library. PHPExcel is a library written in pure PHP and provides a set of classes that allow you to write to and read from different spreadsheet file formats.

The web applications may contain data in various formats or they may have to collect data from various sources. It is not necessary that all the gathered data be compatible for storage on the server. Most large-scale websites use server-side code to dynamically display different data when needed. A database stores information more efficiently and can handle volumes of information that would be unmanageable in a spreadsheet. Spreadsheets have record limitations, whereas a database does not. So, we need to store this data in a database for future use. Here, we are using the PHPExcel library to import a CSV file into a PHP database. You can easily implement this by following these steps.

These are the steps to import Excel data to MySQL using PHPExcel-

Install PHPExcel with Composer

First, we need to install the PHPExcel library to read excel data. You can either download this from Github or install it using Composer. If your system does not have composer installed, then first download the latest composer version from its official website-

You can check a successful installation using the following command on cmd

Now, go to your project directory on the command prompt and run the following command to install the PHPExcel library.

After this, you will notice that Composer has downloaded all libraries under the ‘vendor‘ directory of your project root. Here is the file structure of this project-

Excel File

Suppose we have the following excel file containing school program participants data-

Database Script (db.php)

Here, we have written the database connection code. Make sure to replace ‘hostname‘, ‘username‘, ‘password‘ and ‘database‘ with your database credentials and name.

If we want to store or import Excel data into the MySQL database, we need a database table. So, we have a MySQL database ‘school‘ and in it we have to create a ‘participants‘ table with the given columns.

Create Upload File Template

To create a file uploader, we have created a simple HTML file upload form ‘index.php‘. If a form contains any file type input field, then we have to add an attribute ‘encrypt‘ with a value of ‘multipart/form-data‘.

Parse Excel and Insert into Database (uploadexcel.php)

In this PHP code, we have validated the uploaded file type and then included the PHPExcel library files and database configuration file (db.php). We have validated the execution of each logical code. It returns an error message on failure. Further, PHPExcel parses the excel file, reads the data, and stores it in an array. We have looped over this array to insert data into the database and show the response to the web browser.

On successful execution, the data will be inserted in the database as in the given screenshot-

Источник

Import Excel File into MySQL Database using PHP

Database backup and restore is the most important part in maintaining software. Taking periodical automatic backup is must for any project.

In case of unknown security flaw which may collapse your system. In such unfortunate situation, it will be the holy grail to save you if you have a backup.

It is not only enough to take a backup by exporting your database. Also, we need to experiment with importing backup to ensure the restore.

Backup files can be in any format. You may see many of the database clients supports SQL, Excel or CSV format files to import external data.

We are going to create our own PHP database client only for importing Excel data into a database.

Restoring excel backup into a database via programming will save our time. Let us study how to implement a quick restore by importing bulk data from excel files. If you are looking for export example, you may visit my earlier export data in CSV format.

This screenshot shows the output by displaying the list of imported rows from the database.

What is inside?

About this excel import example

This example allows the user to choose the import template via HTML form input. A sample Excel template is added with this downloadable resource.

With valid file, the HTML form submit will call PHP to process Excel parsing.

In PHP, the PHPSpreadSheet library is used for reading the Excel file data and convert it into an array.

By iterating the array data, the code will execute database insert row by row.

File Structure

See the Excel import example’s file structure shown below. The vendor folder has the PHPSpreadsheet library and ites dependacies.

I have given sample import template with this files to experiment the import operation.

The schema.sql has the script to create the target database. You can find the SQL script in the next section.

Database script

Import the following SQL script and create database environment. Also, configure your database details in DataSource.php to make this example working.

Creating UI to upload import template

This HTML form with the file upload option is used to choose the excel source. On submitting this form, the excel file will be sent to the PHP to parse the data source. This file upload option will only allow the excel files to choose by using the accept attribute.

This code also contains the response HTML for displaying the message returned from PHP. This message is shown based on the type of response sent from PHP after excel import.

Parse excel data using PHPSpreadsheet

In this PHP code, I specified the array of allowed file type for the file-type validation in PHP. I validated the uploaded file type along with the array allowed type.

If match found, the code will execute further logic. Otherwise, it will return the error message to the user.

With successful validation, excel file parsing read and convert the data into an array. Each array index has an array of row-data. After reading the non-empty row data, I run the database insert and show the response.

Note: Download PHPSpreadsheet and include into the vendor directory.

Источник

How to import data from Excel to List in PHP

EasyXLS Excel library can be used to import Excel files with PHP on Windows, Linux, Mac or other operating systems. The integration vary depending on the operating system or if .NET Framework or Java is chosen:

1. EasyXLS on Windows using .NET Framework (COM+) with PHP

2. EasyXLS on Linux, Mac, Windows using Java with PHP

EasyXLS on Windows using .NET Framework (COM+) with PHP

If you opt for the COM+ version of EasyXLS, be sure that you have EasyXLS installed and registered on your machine.

Step 1: Download and install EasyXLS Excel Library for COM+

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Verify if COM and .NET extension is enabled in PHP

Check PHP.ini for [COM_DOT_NET] extension.

See also

How to enable COM and .NET extension in PHP?

Step 3: Verify if EasyXLS is registered

Check if EasyXLS component is present in Component Services.

See also

How to verify if EasyXLS is registered?

Step 4: Run PHP code that imports data from Excel to DataSet

Execute the following PHP code that imports Excel data to DataSet.

Overloaded methods
For methods with same name but different parameters, only the first method overload retains the original name. Subsequent overloads are uniquely renamed by appending to the method name ‘_2’, ‘_3’, etc (method, method_2, method_3), an integer that corresponds to the order of declaration that can be found in EasyXLS.h, a file that comes with EasyXLS installation.

EasyXLS on Linux, Mac, Windows using Java with PHP

If you opt for the Java version of EasyXLS, a similar code as above requires PHP/Java Bridge between PHP and Java.

Step 1: Download EasyXLS Excel Library for Java

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Install PHP/Java Bridge

Step 3: Setup EasyXLS library in Tomcat

Copy EasyXLS.jar into Tomcat installation path, lib folder.

Step 4: Run PHP code that imports data from Excel to DataSet

Execute the following PHP code that imports Excel data to DataSet.

Источник

Заметки программиста

Не так давно появилась задача – загрузить данные из Ecxel файла в базу сайта, и реализовать механизм так, чтобы быстро можно было обновлять эти данные, т.е. загружать новый файл. Решил попробовать парсер Excel-файлов phpExcelReader, но сколько не бился с ним, получал ошибку типа “… is not readable”. Поэтому решил использовать библиотеку PHPExcel.

Загружать будем прайс-лист:

Артикул Наименование Количество Цена Валюта Единица
123456 Апельсин 20 50000 руб килограмм
123457 Мандарин 20 54000 руб килограмм
123458 Яблоко 50 23500 руб килограмм

В таблицу со структурой:

id article name
quantity
price
currency
unit

Скачав архив с библиотекой и открыв его вы увидите несколько папок и файлов – это описание и примеры использования библиотеки. Нам понадобится папка “Classes” – распаковываем архив и загружаем её, например, в корень сайта.

Файл excel можно загрузить в нужную папку на сервере, например uploads, через ftp сервер или создать страницу загрузки с «file» name= «upload_file» . Для меня конечно второй вариант был в приоритете (как реализовать загрузку файла на сервер я писал в статье «Отправка формы и файлов через Ajax»).

Итак, предположим, что форму загрузки мы сделали, библиотеку подключили, начнем писать скрипт обработки файла и загрузки в базу данных.

В принципе, второй цикл можно усовершенствовать, используя количество колонок, но у меня файл всегда будет стандартный, поэтому не вижу в этом смысла.

Источник

Welcome to a tutorial on how to import an Excel Spreadsheet into a MySQL database with PHP. So you have a project that requires reading some data from a spreadsheet and save them into the database? Sadly, PHP cannot read Excel files natively.

In order to import Excel files into the database:

  1. We have to use a third-party library that can read Excel files. PHPSpreadsheet is a good recommendation, and we can get it easily using Composer – composer require phpoffice/phpspreadsheet
  2. Create the database table, and Excel file to import.
  3. Use PHPSpreadsheet to read the Excel spreadsheet, extract the data, and insert them into the database.

Just how exactly is this done? Let us walk through an example in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

Import Excel Spreadsheet Into MySQL With PHP

Fullscreen Mode – Click Here

TABLE OF CONTENTS

DOWNLOAD & NOTES

First, here is the download link to the source code as promised.

QUICK NOTES

  • A copy of PHPSpreadsheet is not included in the zip file. Please download the latest version by yourself.
  • Create a test database and import 2a-dummy.sql.
  • Change the database settings in 3-import.php to your own, then launch it in the browser.

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

All right, let us now get into an example of importing an Excel file into the database.

STEP 1) INSTALL PHPSPREADSHEET

There are no native functions in PHP to read Excel files. So we need to download and use a third-party library called PHPSpreadsheet – Here’s how to get it.

  • The easiest way is to use an application manager called Composer – Something like Git, quite a useful one for pulling libraries automatically. A small hassle to download and install, but a one-time effort nonetheless.
  • After installing Composer, open the command prompt and navigate to your project folder – cd HTTP/FOLDER/.
  • Run composer require phpoffice/phpspreadsheet.

That’s all. Composer will automatically pull the latest version into the vendor/ folder.

STEP 2) DUMMY DATABASE TABLE & EXCEL FILE

2A) DUMMY USERS TABLE

2a-dummy.sql

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`);

ALTER TABLE `users`
  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;

For this example, we will use a very simple users table with only 3 fields.

Field Description
id Primary key, auto-increment.
name The user’s name.
email The user’s email address.

2B) DUMMY EXCEL FILE

2b-dummy.xlsx

Name Email
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

Next, we have some dummy users in an Excel file that need to be imported into the above table.

STEP 3) PHP IMPORT SCRIPT

3-import.php

<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
  "mysql:host=$dbhost;charset=$dbchar;dbname=$dbname",
  $dbuser, $dbpass, [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
 
// (B) PHPSPREADSHEET TO LOAD EXCEL FILE
require "vendor/autoload.php";
$reader = new PhpOfficePhpSpreadsheetReaderXlsx();
$spreadsheet = $reader->load("2b-dummy.xlsx");
$worksheet = $spreadsheet->getActiveSheet();

// (C) READ DATA + IMPORT
$sql = "INSERT INTO `users` (`name`, `email`) VALUES (?,?)";
foreach ($worksheet->getRowIterator() as $row) {
  // (C1) FETCH DATA FROM WORKSHEET
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false);
  $data = [];
  foreach ($cellIterator as $cell) { $data[] = $cell->getValue(); }

  // (C2) INSERT INTO DATABASE
  print_r($data);
  try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    echo "OK - USER ID - {$pdo->lastInsertId()}<br>";
  } catch (Exception $ex) { echo $ex->getMessage() . "<br>"; }
  $stmt = null;
}

// (D) CLOSE DATABASE CONNECTION
if ($stmt !== null) { $stmt = null; }
if ($pdo !== null) { $pdo = null; }

Yep, this one looks a little intimidating at first but is actually very straightforward.

  1. Connect to the database. Remember to change the settings to your own.
  2. Load the PHPSpreadsheet library, and use it to open the dummy Excel spreadsheet.
  3. Read the cells of the spreadsheet, and import them into the database.
  4. The end. Close the database connection.

SPREADSHEETS WITH FORMULA

Take note that PHPSpreadSheet will not evaluate the cell formula. Do your own “convert formulas to values” in Excel, and save it as a different spreadsheet before importing.

DATE & TIME CELLS

This is yet another gotcha… Basically, convert the date/time cell into a string or text first.

LINKS & REFERENCES

  • Need to do the opposite of exporting into Excel files? – Here’s how.
  • Check out the PHPSpreadsheet GitHub Page here.
  • Also, the official documentation.

YOUTUBE TUTORIAL

INFOGRAPHIC CHEAT SHEET

How To Import Excel Files In PHP MySQL (click to enlarge)

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Like this post? Please share to your friends:
  • Php csv для excel
  • Php csv for excel
  • Php creating excel file
  • Php content type word
  • Php application vnd ms excel