php - 如何在 PhpSpreadsheet 中获取第一列索引
问题描述
我必须遍历 xls 文档前两列的所有行。问题是该特定文档的第一列是“G”,索引为 7。
有什么方法可以获取第一列索引,因为我不想对其进行硬编码。
我的循环:
$spreadsheet =\PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
$rows = [];
for ($row = 1; $row <= $highestRow; ++$row) {
// I WANT TO REPLACE HARD-CODED VALUES OF 7 AND 8
// WITH $firstCol and $firstCol+1
for ($col = 7; $col <= 8; ++$col) {
$value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
$rows[$row][$col] = $value;
}
}
解决方案
您可以添加一个while循环来跳过空单元格。尝试这个:
$rows = [];
for ($row = 1; $row <= $highestRow; ++$row) {
$col = 1;
$cell = $worksheet->getCellByColumnAndRow($col, $row);
// Skip empty cells
while (in_array($cell->getValue(), [null, ''], true)) {
$col++;
$cell = $worksheet->getCellByColumnAndRow($col, $row);
}
$maxCol = $col + 1;
for ( ; $col <= $maxCol; ++$col) {
$value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
$rows[$row][$col] = $value;
}
}
推荐阅读
- reactjs - 如何修复 setState 打字稿参数错误?
- windows - 如何为 WPA2 Enterprise AES 导出已保存的用户凭据
- c# - 在 Azure 函数中使用 Serilog.ILogger
- regex - 正则表达式 Oracle 与预期不匹配
- oracle11g - 在无约束表上插入,导致外键引用的表中出现 ora-02449 唯一/主键
- excel - Excel:将单元格的条件格式颜色复制到具有相同值的所有单元格
- c - 如何使用libmodbus,使用makefile?
- sql - WHERE colname LIKE '% %' OR colname LIKE '% % %' 返回包含四个单词的行
- json - JSONDecodeError:期望值:从 Pokemon API 获取数据时的第 1 行第 1 列(字符 0)
- c++ - 如何在链接列表中创建二进制搜索?