PhpSpreadsheet 导出函数支持超过26个字段

使用 PhpSpreadsheet 默认导出时,仅支持26个列内的数据。超出26个列时默认被截掉,以下为 php 实现 Excel 导出示例,并支持超过26个字段数据。

这26列分别是大写字母 A-Z,PhpSpreadsheet 本身支持 AA、AB、AAA、AAB 这样的多列写法。

// 将索引转换为Excel的列字母(仅返回A-Z)
function get_column_index($index): string
{
    if ($index >= 0 && $index < 26) {
        // 如果是 A 到 Z 之间的列,直接返回对应的字母
        return chr(65 + $index);
    } else {
        // 针对 AA、AB、AC ... ZZ 这样的列,使用类似递归的方式计算出对应的字母组合
        $result = '';
        while ($index >= 26) {
            $result .= chr(65 + ($index % 26));
            $index = intval($index / 26) - 1;
        }
        $result .= chr(65 + $index);
        return strrev($result); // 需要反转列名字母组合
    }
}

// 导出文件函数
function excel_export(string $title = "", array $header = [], array $data = [], string $filename = '')
{
    if (empty($filename )) $filename = 'export';
    $filename .= "_" . date("Ymd");
    $spreadsheet = new Spreadsheet();
    
    $objPHPExcel = $spreadsheet->getActiveSheet();
    $objPHPExcel->setTitle($title);
    $objPHPExcel->setCellValue('A1', $title);
    
    // 设置表头
    foreach ($header as $k => $v) {
        $column = get_column_index($k); // 使用自定义函数
        $objPHPExcel->setCellValue($column . '1', $v);
    }
    
    $rowIndex = 2;
    foreach ($data as $rows) { // 行写入
        foreach ($rows as $keyName => $value) { // 列写入
            $index = array_flip(array_keys($rows))[$keyName];
            $column = get_column_index($index);
            $objPHPExcel->setCellValue($column . $rowIndex, $value);
        }
        $rowIndex++;
    }
    
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");
    header('Content-Disposition:attachment;filename=' . $filename. '.xlsx');
    header("Content-Transfer-Encoding:binary");
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    //删除临时的sheet
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
    exit;
}

参考:
PHPExcel 库中的 PhpSpreadsheet 导出函数支持超过26个字段的通用函数_清风云襄的博客-CSDN博客
Http 下载文件header头参数 – 飞刀寻欢 – 博客园 (cnblogs.com)

Author: thinkwei

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注