xlswrite设置多级表头

2021-07-21

xlswrite是一个高效的excel导入导出扩展 文档地址:https://xlswriter-docs.viest.me/

/**
 * @description: 根据数组设置多级表头
 * @param object $file_object excel表格对象
 * @param array $datas 表头数组
 * @param int $row 开始行数,从1开始算
 * @param int $level 层级
 * @return array 表头对应的数据的key
 */
function _set_header_by_array($file_object, $datas, $row, $level = 0)
{
	// 索引
	static $index = 0;
	static $keys  = [];
	foreach ($datas as $data) {
		if ($data['key']) {
			$keys[] = $data['key'];
		}
		$new_row = $row + $level;
		if ($data['length'] == 1 && $data['height'] == 1) {
			$file_object->insertText($new_row - 1, $index, $data['value']);
		} else {
			$index1 = \Vtiful\Kernel\Excel::stringFromColumnIndex($index);
			$index2 = \Vtiful\Kernel\Excel::stringFromColumnIndex($index + $data['length'] - 1);
			$file_object->mergeCells($index1 . $new_row . ':' . $index2 . ($new_row + $data['height'] - 1), $data['value']);
		}
		if (!empty($data['children'])) {
			_set_header_by_array($file_object, $data['children'], $row, $level + 1);
		} else {
			$index += $data['length'];
		}
	}
	return $keys;
}
/**
 * @description: 
 * @param key 数据对应的key,为空则不获取
 * @param value 表头文字
 * @param height 纵向单元格数
 * @param length 横向单元格数
 * @param children 子集表头
 */
$data = [
    ['key' => '', 'value' => '内容', 'height' => 3, 'length' => 1, 'children' => []],
    [
        'key' => '', 'value' => '项目', 'height' => 1, 'length' => 4, 'children' => [
            [
                'key' => '', 'value' => '计划', 'height' => 1, 'length' => 2, 'children' => [
                    ['key' => 'a1', 'value' => '计划1', 'height' => 1, 'length' => 1, 'children' => []],
                    ['key' => 'a2', 'value' => '计划2', 'height' => 1, 'length' => 1, 'children' => []],
                ]
            ],
            [
                'key' => '', 'value' => '实际', 'height' => 1, 'length' => 2, 'children' => [
                    ['key' => 'a3', 'value' => '实际1', 'height' => 1, 'length' => 1, 'children' => []],
                    ['key' => 'a4', 'value' => '实际2', 'height' => 1, 'length' => 1, 'children' => []],
                ]
            ],
        ],
    ],
    [
        'key' => '', 'value' => '问题', 'height' => 1, 'length' => 5, 'children' => [
            ['key' => 'a23', 'value' => '合计', 'height' => 2, 'length' => 1, 'children' => []],
            ['key' => 'a24', 'value' => '问题1', 'height' => 2, 'length' => 1, 'children' => []],
            ['key' => 'a25', 'value' => '问题2', 'height' => 2, 'length' => 1, 'children' => []],
            ['key' => 'a26', 'value' => '问题3', 'height' => 2, 'length' => 1, 'children' => []],
            ['key' => 'a27', 'value' => '问题4', 'height' => 2, 'length' => 1, 'children' => []],
        ],
    ],
    ['key' => 'a21', 'value' => '问题线索', 'height' => 3, 'length' => 1, 'children' => []],
    ['key' => 'a22', 'value' => '案件线索', 'height' => 3, 'length' => 1, 'children' => []],
];
_set_header_by_array($file_object, $data, 3, 0);

 

{/if}