Php – How to read data from excel using with PHPExcel

PHPphpexcel

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.

Best Answer

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
Related Topic