I have an excel file that looks something like this
What I want to do is read the data from all rows but not all columns. I want to fetch data for all rows from column A to E . Currently, I am able to read the entire row (column A to CL ) with this code
// Read data from excel file
$reader = IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($inputFileName);
// Convert read data to array
$sheetData = $spreadsheet->getActiveSheet()->toArray(null,true,true,true);
// Put captured array to use
for ($row=1; $row <= count($sheetData) ; $row++) {
$xData = "'".implode("','",$sheetData[$row])."'";
}
print_r($xData);
exit;
Could someone guide me achieve this? I tried
// Specify columns to fetch data from
$cols = array('A','B','C','D','E','F','G','H','I','J','K');
// Put captured array to use
for ($row=1; $row <= count($sheetData) ; $row++) {
foreach ($cols as $col) {
$xData = "'".implode("','",$sheetData[$col.$row])."'";
}
}
print_r($xData);
exit;
but that didn't work.
Use utility helper eg PhpOffice\\PhpSpreadsheet\\Cell\\Coordinate to convert column to/from index/letter.
$ws = $spreadsheet->getActiveSheet();
$firstColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString('A'); // A->1
$lastColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString('E'); // E->5
$firstRow = 1;
$lastRow = 4;
$data = [];
for($row = $firstRow; $row <= $lastRow; ++$row){
for($col = $firstColumnIndex; $col <= $lastColumnIndex; ++$col){
$data[$row][$col] = $ws->getCellByColumnAndRow($col, $row)->getValue();
}
}
print_r($data, true); // data are now collected in 2-dimensional array
There are also other methods such as stringFromColumnIndex
, coordinateFromString
, indexesFromString
, buildRange
, rangeBoundaries
, rangeDimension
, getRangeBoundaries
etc. which may come handy, but seems not so well documented.
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.