[英]Fetch range of columns with PhpSpreadsheet
I have an excel file that looks something like this我有一个看起来像这样的 excel 文件
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 .
我想获取从列A到E的所有行的数据。 Currently, I am able to read the entire row (column A to CL ) with this code
目前,我可以使用此代码读取整行(从 A到CL列)
// 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.使用实用程序助手,例如PhpOffice\\PhpSpreadsheet\\Cell\\Coordinate将列转换为索引/字母。
$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.还有其他方法,例如
stringFromColumnIndex
、 coordinateFromString
、 indexesFromString
、 buildRange
、 rangeBoundaries
、 rangeDimension
、 getRangeBoundaries
等,它们可能会派上用场,但似乎没有很好的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.