简体   繁体   中英

PHPExcel reading specific columns

I'm using PHPExcel to read an xls file, here is my code:

require('PHPExcel/PHPExcel.php'); 
$Reader = PHPExcel_IOFactory::createReaderForFile($xls_path);
$Reader->setReadDataOnly(true);
$objXLS = $Reader->load($xls_path);
$data = $objXLS->getActiveSheet()->toArray(null, true, true, true);
$objXLS->disconnectWorksheets();
unset($objXLS);
var_dump($data);

the output is :

Array
        (
            [A] => 1001
            [B] => XXX
            [C] => AAZ878
            [D] => 19233
            [E] => pppp
            [F] => oooo
            [G] => 276
            [H] => Y
        )

how can I specify in my code to read only columns A,B and H so that the output will be

Array
        (
            [A] => 1001
            [B] => XXX
            [H] => Y
        )

Thanks

You can't with toArray() ; but you could then easily do an array_walk(), with a callback that modified each subarray into just those columns that you wanted. Something like:

$columns = array_fill_keys(['A', 'B', 'H'], true);
array_walk(
    $data,
    function(&$row) use ($columns) {
        $row = array_intersect_key($row, $columns);
    }
);

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