You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PhpSpreadsheet中完成一列数据写入后如何切换到下一列

PhpSpreadsheet 垂直写入数据切换列解决方案

核心逻辑

PhpSpreadsheet 支持通过「数字列索引+行号」定位单元格,垂直写入同一列时固定列索引、遍历行号写入即可,完成单列写入后将列索引+1即可切换到下一列,重复写入逻辑即可。

可运行代码示例

<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// 实例化表格
$spreadsheet = new Spreadsheet();
$activeSheet = $spreadsheet->getActiveSheet();

// 按照列维度组织的二维数组,每个子数组对应单列的垂直数据
$columnData = [
    ['姓名', '张三', '李四', '王五'], // A列数据
    ['年龄', '25', '30', '28'], // B列数据
    ['部门', '技术部', '产品部', '运营部'] // C列数据
];

$startCol = 0; // 起始列索引,A列对应0,B对应1,以此类推
$startRow = 1; // 起始行号,Excel第一行对应行号1

// 遍历每一列的数据
foreach ($columnData as $singleColData) {
    $currentRow = $startRow;
    // 垂直写入当前列的所有行数据
    foreach ($singleColData as $cellValue) {
        $activeSheet->setCellValueByColumnAndRow($startCol, $currentRow, $cellValue);
        $currentRow++;
    }
    // 切换到下一列
    $startCol++;
}

// 导出保存
$writer = new Xlsx($spreadsheet);
$writer->save('测试导出.xlsx');

扩展说明

  • 如需将数字列索引转换为Excel列字母,可调用工具方法:\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex)
  • 如需从指定位置开始写入,修改$startCol和$startRow的初始值即可

参考报告示例

报告示例图

原数据参考

我的数据图

内容的提问来源于stack exchange,提问作者Linh Lê Nhật

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:15:02