简体   繁体   中英

How to read data from excel using with 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.

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

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);

Try this so you can jump start the development process:

include '.... /PHPexcel/Classes/PHPExcel.php';
    $dataFfile = "C:/tmp/test_data.xls";
    $objPHPExcel = PHPExcel_IOFactory::load($dataFfile);
    $sheet = $objPHPExcel->getActiveSheet();
    $data = $sheet->rangeToArray('A2:AB5523');
    echo "Rows available: " . count($data) . "\n";
    foreach ($data as $row) {
        print_r($row);
    }

Replace the include path with your path to the PHPExcel.php
Replace $dataFile with your excel file
Also adjust the range of the cells that you want to import

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM