Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data from excel using with PHPExcel

Tags:

php

phpexcel

I am trying to import data from excel sheet(.xlsx). I have found PHPExcel for import data but after downloading document and source code I am confused which file is important for me. I also tried to find out document on that site but not found the way.

About my task: Read excel sheet data from selected sheet and insert data to my database table.

So I really thankful If You will guide me how to use it.

Thanks.

like image 827
Manan Avatar asked Oct 12 '14 05:10

Manan


Video Answer


2 Answers

You can use the PHPExcel library to read an Excel file and insert the data into a database.

Sample code is below.

//  Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';

$inputFileName = 'sample.xls';

//  Read your Excel workbook
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());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();

//  Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){ 
    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                    NULL,
                                    TRUE,
                                    FALSE);
    //  Insert row data array into database here using your own structure
like image 157
Brainy Prb Avatar answered Oct 06 '22 00:10

Brainy Prb


From a quick look over the documentation, use the IOFactory to automatically determine the file format.

include 'path/to/PHPExcel/IOFactory.php';

// Let IOFactory determine the spreadsheet format
$document = PHPExcel_IOFactory::load('path/to/spreadsheet.xls');

// Get the active sheet as an array
$activeSheetData = $document->getActiveSheet()->toArray(null, true, true, true);

var_dump($activeSheetData);
like image 21
Tserkov Avatar answered Oct 06 '22 00:10

Tserkov