目录

需求

项目中数据需要导出Excel,数据格式如下

[
  {
    "produce_no": "GD20210331-001",
    "client_info": "客户一",
    "url": "blog.68hub.com",
    "order_items": [
      {
        "produce_order_id": 5070,
        "produce_name": "产品一",
        "price": "2222.00",
        "created_at": "2021-03-31"
      },
      {
        "produce_order_id": 5070,
        "produce_name": "产品二",
        "price": "2222.00",
        "created_at": "2021-03-31"
      },
      {
        "produce_order_id": 5070,
        "produce_name": "产品三",
        "price": "2222.00",
        "created_at": "2021-03-31"
      }
    ]
  },
  {
    "produce_no": "GD20210331-002",
    "client_info": "客户二",
    "url": "blog.68hub.com",
    "order_items": [
      {
        "produce_order_id": 5070,
        "produce_name": "产品一",
        "price": "2222.00",
        "created_at": "2021-03-31"
      }
    ]
  }
]

Excel表中需要将有多个order_items 数据的客户主要信息(client_info,url等)进行合并(合并单元格)

解决方案

...
$excel = new \Vtiful\Kernel\Excel($config);
$fileObj = $excel->fileName($fileName);
$fileObj->header(['订单号','客户信息','url','产品名称','价格'])

$line = 1; //跳过表头
foreach ($data as $item){
    //先遍历子表中的数据
    $num = 0;
    foreach($item['order_items'] as $val){
        $fileObj->insertText($line+$num, 3, $val['produce_name']);
        $fileObj->insertText($line+$num, 4, $val['price']);
        $num++;
    }
    //合并父表中相同数据
    $fileObj->mergeCells(sprintf("%s%d:%s%d","A", $line+1, "A", $line+$num), $item['product_no']);
    $fileObj->mergeCells(sprintf("%s%d:%s%d","B", $line+1, "B", $line+$num), $item['client_info']);
    $fileObj->mergeCells(sprintf("%s%d:%s%d","C", $line+1, "C", $line+$num), $item['url']);
    $line = $line +$num;
}
$filePath = $fileObj->output();
...

文档