php - 在 PHPSpreadsheet 中迭代时如何获取单元格坐标?

标签 php excel phpspreadsheet

我试图在 PHPSpreadsheet 中填充和着色一些标题。列数可以是可变的。文档中建议将单元格设置为范围,因此我需要知道最后一个单元格的坐标才能执行此操作。

我已经尝试在遍历列时使用 getCellByColumnAndRow 但这会返回单元格的值而不是坐标:

$i = 1;
$lastCellValue = null;

foreach ($headers as $header) {
    $sheet->setCellValueByColumnAndRow($i, 1, $header);
    $lastCellValue = $sheet->getCellByColumnAndRow($i, 1);
    $i++;
}

$spreadsheet->getActiveSheet()->getStyle('A1:'.$lastCellValue)->getFill()
    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFFF0000');

迭代时如何获取最后一个单元格的坐标?

最佳答案

getCellByColumnAndRow() 不返回单元格值,它返回单元格对象....并且该单元格对象有许多方法,包括 getColumn()getRow()getCoordinate()

所以

foreach ($headers as $header) {
    $sheet->setCellValueByColumnAndRow($i, 1, $header);
    $lastCellAddress = $sheet->getCellByColumnAndRow($i, 1)->getCoordinate();
    $i++;
}

$spreadsheet->getActiveSheet()->getStyle('A1:'.$lastCellAddress)->getFill()
    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFFF0000');

关于php - 在 PHPSpreadsheet 中迭代时如何获取单元格坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48420538/

相关文章:

具有大数据的 PhpSpreadsheet

javascript - 如何仅将选定列表中的 1 个值发布到 Controller 代码

PHP 后期静态绑定(bind)引用调用类

excel - 仅允许在 Excel 2007/2010 中保存为 PDF

excel - 逆向工程Excel公式

excel - 如何使所有单元格换行文本并在 Laravel Excel 中完成所有边框

phpspreadsheet - 读取包含图像的 Excel 工作表失败

php 列表类别

javascript - 如何使用 jQuery 将变量发布到 PHP?

excel - 如何等待 Power Query 刷新完成?