Upload file excel php

I want to upload excel file using to php and wanted to perform some file operation in that excel file. I am not able to upload the file , If any one have some Idea please help , in the server side how to get the path from where the file has been uploaded?

$target_dir = ‘uploads/’; is not working for me. and My file is in D: Please help.

PHP CODE:

 <?php    
if(isset($_POST['SubmitButton'])){ //check if form was submitted

$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["filepath"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

require_once dirname(__FILE__) . '/Includes/Classes/PHPExcel/IOFactory.php';

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

$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($target_file);

$i=2;
$val=array();
$count=0;
for($i=2;$i<34;$i++)
{
$val[$count++]=$objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue();
}
//echo'<pre>';print_r($val);
}    
?>

HTML CODE:

<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file"  name="filepath" id="filepath"/></td><td><input type="submit" name="SubmitButton"/>
</body>

asked Jul 26, 2016 at 5:26

anish's user avatar

You first need to upload the file before the read line:

$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["filepath"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

move_uploaded_file($_FILES["filepath"]["tmp_name"], $target_file);

// rest of your code...

now you should be able to continue working on the file.
before this, the file never have been in your uploads folder.

answered Jul 26, 2016 at 5:43

Roey Haim's user avatar

Roey HaimRoey Haim

732 silver badges9 bronze badges

4

if(isset($_POST['SubmitButton'])){
  try {       //attached file formate
    $statement = $db->prepare("SHOW TABLE STATUS LIKE 'table_name'");
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
        $new_id = $row[10]; //10 fixed

    $up_filename=$_FILES["filepath"]["name"];
    $file_basename = substr($up_filename, 0, strripos($up_filename, '.')); // strip extention
    $file_ext = substr($up_filename, strripos($up_filename, '.')); // strip name
    $f2 = $new_id . $file_ext;

    move_uploaded_file($_FILES["filepath"]["tmp_name"],"uploads/" . $f2);

   // Client's info Insert MySQl 
    $statement = $db->prepare("INSERT INTO table_name (files) VALUES (?)");
    $statement->execute(array($f2));

    $success_message = "Excel file upload successfully!";
}
catch(Exception $e) {
        $error_message = $e->getMessage();
}
}

Form code:

 <form action="" method="post" enctype="multipart/form-data"> <input
 type="file"  name="filepath" id="filepath"/></td><td><input
 type="submit" name="SubmitButton"/>
 </form>

answered Jul 26, 2016 at 6:27

Amranur Rahman's user avatar

U did not write code to upload file.

 move_uploaded_file()

answered Jul 26, 2016 at 5:34

Munish Chechi's user avatar

2

You have to move your file from the temporary upload directory to the directory you want it in with the move_uploaded_file() function.

There are 2 arguments you need to put for the move_uploaded_file() function — the temporary file you just uploaded (ex. $_FILES["file"]["tmp_name"]), and then the directory you want to move it to… So it would end up looking something like this: move_uploaded_file($_FILES["file"]["tmp_name"], $path_of_new_file)

answered Jul 26, 2016 at 6:00

Jeremy Board's user avatar

1

Today, We want to share with you how to upload excel file in php.In this post we will show you how to import xlsx file into mysql database using php?, hear for how to display excel file in php we will give you demo and example for implement.In this post, we will learn about Import Excel File Data In Database Using PHP with an example.

How to upload excel file to php server from <input type=“file”>?

Example 1: index.php

<?php
if(isset($_POST["submit"]))
{

                $url='127.0.0.1:8080';
                $dbUser='root';
                $dbPasswrod='';
                $link_new=mysqli_connect($url,$dbUser,$dbPasswrod,"location");
          if(!$link_new){
          die('Could not Connect My Sql:' .mysqli_error());
		  }
          $file = $_FILES['file']['tmp_name'];
          $handle = fopen($file, "r");
          $c = 0;
          while(($allfiles = fgetcsv($handle, 1000, ",")) !== false)
                    {
          $fname = $allfiles[0];
          $lname = $allfiles[1];
          $query_s = "insert into excel(fname,lname) values ('$fname','$lname')";
          $stmt = mysqli_prepare($link_new,$query_s);
          mysqli_stmt_execute($stmt);

         $c = $c + 1;
           }

            if($query_s){
               echo "Good Luck sucess";
             } 
		 else
		 {
            echo "Sorry! Unable to impo.";
          }

}
?>
<!DOCTYPE html>
<html>
<body>
<form enctype="multipart/form-data" method="post" role="form">
    <div class="dsp form-group">
        <label for="exampleInputFile">File Upload</label>
        <input type="file" name="file" id="file" size="150">
        <p class="help-block">Only Excel/CSV File Import.</p>
    </div>
    <button type="submit" class="btn btn-default" name="submit" value="submit">Upload</button>
</form>
</body>
</html>

PHP – import excel file into mysql database tutorial

db_config.php

<?php
	$dbHost = "127.0.0.1:8080";
	$dbDatabase = "h_php";
	$dbPasswrod = "root";
	$dbUser = "root";
	$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
?>

Create index.php file

<!DOCTYPE html>
<html>
<head>
	<title>Excel Uploading PHP - www.pakainfo.com</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">
	<h2>Excel Upload</h2>


	<form method="POST" action="excelUpload.php" enctype="multipart/form-data">
		<div class="dsp form-group">
			<label>Upload Excel File</label>
			<input type="file" name="file" class="form-control">
		</div>
		<div class="dsp form-group">
			<button type="submit" name="Submit" class="btn btn-success">Upload</button>
		</div>
		<p>Download Demo File from here : <a href="demo.ods"><strong>Demo.ods</strong></a></p>
	</form>
</div>


</body>
</html>

Create excelUpload.php file

<?php


require('library/php-excel-reader/excel_reader2.php');
require('library/SpreadsheetReader.php');
require('db_config.php');


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


  $mimes = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.oasis.opendocument.spreadsheet'];
  if(in_array($_FILES["file"]["type"],$mimes)){


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


    $Reader = new SpreadsheetReader($fullpathofpicstore);


    $totalSheet = count($Reader->sheets());


    echo "You have total ".$totalSheet." sheets".


    $html="<table border='1'>";
    $html.="<tr><th>Title</th><th>Description</th></tr>";

    for($i=0;$i<$totalSheet;$i++){


      $Reader->ChangeSheet($i);


      foreach ($Reader as $product)
      {
        $html.="<tr>";
        $title = isset($product[0]) ? $product[0] : '';
        $description = isset($product[1]) ? $product[1] : '';
        $html.="<td>".$title."</td>";
        $html.="<td>".$description."</td>";
        $html.="</tr>";


        $query = "insert into products(title,description) values('".$title."','".$description."')";


        $mysqli->query($query);
       }


    }


    $html.="</table>";
    echo $html;
    echo "<br />Data Inserted in dababase";


  }else { 
    die("<br/>Sorry, File type is not allowed. Only Excel file."); 
  }


}


?>

I hope you get an idea about How to Import Excel File into Mysql Database Table in PHP?.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


In this tutorial, we will learn how to import an Excel sheet into database using Spout Library. For that, we will create a Database to insert an excel data into table, a form to make a view to upload an excel sheet and also create a PHP script to perform operation to insert data into Database.

Download This Library

We need to download This Library to use to retrieve data from an Excel sheet.

Create a Database

To insert excel data into MySql database, we need to create a database named as ‘demo_data’ and create a table named as ‘excel_data’

Database: `demo_data`

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


Table structure for table `excel_data`


CREATE TABLE IF NOT EXISTS `excel_data` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` int(11) NOT NULL,
  `email` int(11) NOT NULL,
  `phone` int(11) NOT NULL,
  `city` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) 

Demo Excel Sheet

I am going to show demo excel sheet to be uploaded in this example.
Excelsheet

Create a Form

We will create a form to upload an excel sheet, So create a new file form.html.
Here is the code:

<form  action="http://localhost/uploadExcel.php" method="POST" 
           enctype="multipart/form-data">

  <input type="file"  name="file" >
 
 <input type= "submit" value ="Upload" >
 
</form>

form

Create a PHP File

Now, we will create a file named as uploadExcel.php. Within this file, we will use PHP Script to insert data into table. We need to extract a downloaded zip file and do not forget to include file of Spout library in uploadExcel.php file.
Here is the script to get data from excel sheet.

<?php 

$servername = "localhost";
$username = "your user name";
$password = "your root password";
$dbname = "demo_data";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} 

echo "connected";

use BoxSpoutReaderReaderFactory;
use BoxSpoutCommonType;

// Include Spout library 
require_once 'here is your path of spout library/spout-2.4.3/src/Spout/
                                             Autoloader/autoload.php';

// check file name is not empty
if (!empty($_FILES['file']['name'])) {
     
    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);
    
    // check file has extension xlsx, xls and also check 
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls') 
           && $_FILES['file']['size'] > 0 ) {
        
        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name']; 
   
        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array(); 
        
        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {
            
            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet, 
                // header is in the first row. 
                if ($count > 1) { 

                    // Data of excel sheet
                    $data['name'] = $row[0];
                    $data['email'] = $row[1];
                    $data['phone'] = $row[2];
                    $data['city'] = $row[3];
                    
                    // Push all data into array to be insert as 
                    // batch into MySql database.  
                    array_push($rows, $data);
                }
                $count++;
            }

            // Print All data
            print_r($rows);

            // Now, here we can insert all data into database table.

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";
    
}
?>

learngopani

My Name is Jay Gopani. I Have Create This WebSite. My BirthDate is 01/01/1998. My BirthPlace is Morbi , Dist — Morbi , State — Gujrat.

Содержание

  1. Реализация быстрого импорта из Excel на PHP
  2. Что использовать в качестве инструмента?
  3. Наша боль, как разработчиков
  4. И тут нас отпустило.
  5. Полученные результаты производительности
  6. Загрузка Excel-файла в базу данных MySQL с помощью PHP
  7. Устанавливаем библиотеку PHPSpreadsheet:
  8. Комментарии ( 0 ):
  9. PHP import Excel data to MySQL using PHPExcel
  10. These are the steps to import Excel data to MySQL using PHPExcel-
  11. Install PHPExcel with Composer
  12. Excel File
  13. Database Script (db.php)
  14. Create Upload File Template
  15. Parse Excel and Insert into Database (uploadexcel.php)
  16. Reading and Writing Excel (XLSX) Files in PHP
  17. Best PHP Libraries to Parse and Write Excel Files​
  18. Install Box/Spout library​
  19. Excel (XLSX) File Example​
  20. Read an Excel File (XLSX)​
  21. Write an Excel File (XLSX)​
  22. Read a Large Excel File Efficiently while Using Low Memory​

Реализация быстрого импорта из 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-файлов на свой сервис.

Источник

Загрузка Excel-файла в базу данных MySQL с помощью PHP

Доброго времени суток! В прошлой статье я рассказывал Вам о библиотеке PHPSpreadsheet. Там мы рассмотрели пример записи данных в Excel файл. В данной же статье мы прочитаем с Вами Excel файл и загрузим строки из него в базу данных MySQL.

Зачем это может понадобиться? Одной из самых часто встречающихся задач при работе с интернет-магазинами является загрузка больших прайс-листов в базу данных. Делать это вручную, очевидно, не хочется, да и не стоит, так как увеличивается шанс ошибиться при вводе однотипных данных. А скрипт, который я покажу Вам далее справится с этой задачей достаточно просто — в конечном счете все будет упираться в структуру Вашего Excel файла.

Устанавливаем библиотеку PHPSpreadsheet:

Функция, которая загружает данные в базу:

// возвращает количество листов в книге
$sheetsCount = $spreadsheet->getSheetCount();

// проходимся по каждому листу
for ($c = 0; $c getSheet($c);
// последняя строка в листе
$highestRow = $sheet->getHighestRow(‘A’);

print «Количество строк в книге #$sheetNames[$c] составляет $highestRow» . PHP_EOL;

// SQL-запрос на вставку данных в базу
$sql = «INSERT INTO products (
category, subcategory, name, price, producer, quantity, produced_at
)
VALUES (:category, :subcategory, :name, :price, :producer, :quantity, :produced_at)»;

// подготовленное SQL-выражение
$stmt = $pdo->prepare($sql);

// проходимся по каждой строке в листе
// счетчик начинается с 2-ой строки, так как первая строка — это заголовок
for ($i = 2; $i getCell(‘A’ . $i)->getValue();
$subcategory = $sheet->getCell(‘B’ . $i)->getValue();
$name = $sheet->getCell(‘C’ . $i)->getValue();
$price = $sheet->getCell(‘D’ . $i)->getValue();
$producer = $sheet->getCell(‘E’ . $i)->getValue();
$quantity = $sheet->getCell(‘G’ . $i)->getValue();

// преобразуем дату из формата Excel в формат PHP
$produced_at = PHPSpreadsheetDate::excelToDateTimeObject($sheet->getCell(‘F’ . $i)->getValue());

$stmt->bindParam(‘:category’, $category);
$stmt->bindParam(‘:subcategory’, $subcategory);
$stmt->bindParam(‘:name’, $name);
$stmt->bindParam(‘:price’, $price);
$stmt->bindParam(‘:producer’, $producer);
$stmt->bindParam(‘:quantity’, $quantity);
$stmt->bindParam(‘:produced_at’, $produced_at);
$res = $stmt->execute();

// если запрос на вставку выполнился успешно, выводим в консоль сообщение
if($res) <
print «Строка #$i из листа $sheetNames[$c] помещена в базу» . PHP_EOL;
>
>
>
>

Файл, в котором будет вызываться функция:

PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];

// подключение к базе
$pdo = new PDO($dsn, $user, $pass, $opts);

// класс, который читает файл прайса
$reader = new Xlsx();
// получаем Excel-книгу
$spreadsheet = $reader->load(‘products_db_01012020.xlsx’);

// замеряем время работы скрипта
$startTime = microtime(true);
// запускаем экспорт данных
excel2db($spreadsheet, $pdo, false);
$elapsedTime = round(microtime(true) — $startTime, 4);

print «Скрипт выполнился за: $elapsedTime с.»;

Таким образом, после запуска данного скрипта через некоторое время (от

15 минут при 10 тыс. строк) вы получите содержимое Вашего прайса в базе данных. Конечно это демонстрационный скрипт: в нем нет обработки исключений и возможных ошибок, а также окончательная версия Вашего скрипта может существенно отличаться от приведенной здесь. Это зависит от объема и сложности конкретного прайс-листа.

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

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

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Она выглядит вот так:

  • BB-код ссылки для форумов (например, можете поставить её в подписи):
  • Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    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-

    Источник

    Reading and Writing Excel (XLSX) Files in PHP

    Excel is the most used file format to share data.

    In this tutorial, we will learn how to read and write XLSX files in PHP with the help of examples.

    Last but not least, we’ll parse an Excel file of 1 million lines in PHP in a very fast and memory-efficient manner.

    The whole code and examples are available in a GitHub repository; it comes packaged as a simple Symfony project and provides a Docker image.

    Best PHP Libraries to Parse and Write Excel Files​

    Several libraries allow to work with Excel files; they come with their pros and cons.

    The most famous is phpoffice/phpspreadsheet ; it has more than 10k stars on GitHub. This library allows reading, creating, and writing spreadsheet documents in PHP. This library was formerly named phpoffice/phpexcel , the project has been deprecated in 2017, and phpspreadsheet officially replaced phpexcel .

    The challenger is box/spout ; it has more than 4k stars on GitHub. This library allows reading and writing spreadsheet files in a fast and scalable way.

    There is no debate regarding the support of different file formats: phpoffice/phpspreadsheet supports far more formats, especially the oldest ones which are very convenient when you need to parse XLS files created with Excel 2003 97, or 95.

    Format Support phpoffice/phpspreadsheet box/spout
    Office Open XML (.xlsx) Excel 2007+
    SpreadsheetML (.xml) Excel 2003
    BIFF 8 (.xls) Excel 97
    BIFF 5 (.xls) Excel 95
    Open Document Format (.ods)
    CSV

    When it comes to performance, the big difference is that phpoffice/phpspreadsheet loads the whole XML document in memory while box/spout streams the Excel document’s parsing, allowing it to consume very little memory.

    Which PHP Excel Library should you use?

    Use case Best Library Choice
    Read or write modern and old Excel formats phpoffice/phpspreadsheet
    Read or write XLSX files efficiently or parse large files. box/spout

    There are other libraries, but they don’t bring anything more or very different.

    Both phpspreadsheet and spout also cover the classic operations of reading and writing CSV files in PHP.

    Install Box/Spout library​

    Let’s start by installing box/spout library.

    It provides a simple code API to read or create spreadsheets. Its main advantage is to manipulate large files in a memory-efficient manner.

    Excel (XLSX) File Example​

    We’ll use an XLSX file with a single tab containing tabular data about movies in the following example.

    id title poster overview release_date genres
    299537 Captain Marvel https://. /mWII.jpg The story follows Carol Danvers as she becomes one of the universeu2019s most [. ] 1551830400 Action, Adventure, Science Fiction
    299536 Avengers: Infinity War https://. /3VAd.jpg As the Avengers and their allies have continued to protect the world from threats [. ] 1526346000 Action, Adventure, Science Fiction
    157336 Interstellar https://. /BvIx.jpg Interstellar chronicles the adventures of a group of explorers who make use of a [. ] 1415145600 Adventure, Drama, Science Fiction

    Read an Excel File (XLSX)​

    We parse our existing XLSX file:

    1. Create the Excel Reader using ReaderEntityFactory::createXLSXReader()
    2. Open the XSLX file with $reader->open($path)
    3. Browse each Sheet of the spreadsheet with $reader->getSheetIterator()
    4. Browse each Row of the Sheet with $sheet->getRowIterator()
    5. Browse each Cell of the Row with $row->getCells()
    6. Access each Value of the Cell with $cell->getValue()
    7. Close the Excel Reader (and the File) with $reader->close()

    We can use this snippet to import Excel rows into a database. In that case, we’d need to insert or update data for each parsed row.

    Write an Excel File (XLSX)​

    We write in an XLSX file:

    1. Create the Excel Writer using WriterEntityFactory::createXLSXWriter()
    2. Open the XSLX file with $writer->open($path) that will allow to create the Excel file
    3. Iterate over the rows we want to insert
    4. Create each Excel row with WriterEntityFactory::createRowFromArray($row)
    5. Insert each row in Excel with $writer->addRow($rowFromValues);
    6. Close the Excel Writer (and the File) with $writer->close()

    We can use this snippet to export data to Excel. For instance, by reading rows from a database table to write each row in the XLSX file.

    Besides Microsoft Excel, Google Sheets is getting a lot of traction from users who need to collaborate near real-time on business data. Google offers API to create, read and update Google Sheets data using PHP.

    Read a Large Excel File Efficiently while Using Low Memory​

    A common issue while manipulating large files is memory consumption and reading or writing efficiency.

    The great news is that Spout takes this challenge into account and allows browsing the file content without loading everything in memory.

    Let’s take an example of an xlsx file containing 1M of lines; this file weights 200MB.

    Источник

    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

    Like this post? Please share to your friends:
  • Use different in a sentence for each word
  • Unique values in excel columns
  • Upload excel asp net
  • Use definition to find word
  • Unique text count in excel