Tag Archives: Excel Import To Database

Import data from excel file to php database

excelimport

You have a excel file and if you want to import that excel file to your database then fetch the cell value using this tutorials. you can directly import to your MySQL, Ms SQL and various database using this library and tutorials. just download library and integrate below code there.

Step 1)

Download the excel read library from here. click here for download

Step 2)

Make a form for upload your excel file as below.

<html>
<body>
    <form method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>
                    Select File:
                </td>
                <td>
                    <input type="file" name="file" id="file">
                </td>
            </tr>
            <tr>
                <td colspan="2" align="left">
                    <input type="submit" name="submit" value="Submit">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Step 3)

Now make code for read the excel file cell and import to database as below.

<?php
include('PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');

if(isset($_POST["submit"]))
{
	$inputFileName = $_FILES["file"]["tmp_name"];

	try {
		$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$objPHPExcel = $objReader->load($inputFileName);
	} catch (Exception $e) {
		die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . 
		$e->getMessage());
	}

	$sheet = $objPHPExcel->getSheet(0);
	$highestRow = $sheet->getHighestRow();
	$highestColumn = $sheet->getHighestColumn();

	$newArr = array();
	for($row = 1; $row <= $highestRow; $row++) { 
		$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, null, true, false);

		array_push($newArr, $rowData);
	}

    echo "<pre>";
    print_r($newArr);
	
    echo "Record Update Successfully...";
}
?>

Step 4)

Now upload your excel to form and submit the excel it will return you all cell value which you will insert to your database.