使用 phpSpreadsheet 导出 Excel 完美支持超出26列 和 使用php原生导出 CSV 格式

2021/6/19 17:30:16

本文主要是介绍使用 phpSpreadsheet 导出 Excel 完美支持超出26列 和 使用php原生导出 CSV 格式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

1. 使用 composer 拉取 phpSpreadsheet 包

  composer require phpoffice/phpspreadsheet

2.引入文件

  use PhpOffice\PhpSpreadsheet\Spreadsheet;

3.导出 Excel

/**
 * 导出Excel
 * @param   string  $fileName   文件名称
 * @param   array   $headArr    Excel标题头数组 [['name'=>'标题1', 'width'=>20]] width默认可以没有
 * @param   array   $data       数据内容
 * @param   array   $options    自定义配置信息 ['width'=>15] 目前只有宽度,后续可以增加,可以设置默认宽度
 * @param   string  $suffix     文件后缀,xlsx 和 xls
 * @return  bool
 */
public function exportExcel($fileName = "myData", $headArr = [], $data = [], $options = [], $suffix = 'xlsx')
{
    @ini_set('memory_limit', '2048M');
    @set_time_limit(0);
    if (!$headArr || !$data || !is_array($data)) {
        return false;
    }


    $fileName   .= "_" . date("YmdHis");// 文件名称连接上相应的时间戳信息
    $spreadsheet = new Spreadsheet();
    $objPHPExcel = $spreadsheet->getActiveSheet();
    // 设置表头
    $colum = 'A';
    foreach ($headArr as $k=>$v) { // 循环写入头标题,宽度使用默认值
        $objPHPExcel->setCellValue($colum . '1', $v["name"]);
        if (!empty($v['width'])) {
            $objPHPExcel->getColumnDimension($colum)->setWidth($v['width']);
        } elseif (!empty($options['width'])) {
            $objPHPExcel->getColumnDimension($colum)->setWidth($options['width']);
        }
        $colum++;
    }

    $column = 2;
    // 行写入

    foreach ($data as $datum) { // 循环下查询数据([0=>[0=>[0]]])
        foreach ($datum as $key => $rows) {
            $span = 'A';
            // 列写入
            foreach ($rows as $keyName => $value) {
                $objPHPExcel->setCellValue($span . $column, $value);
                $span++;
            }
            $column++;
        }
    }
    // 重命名表(UTF8编码不需要这一步)
    $fileName = iconv("utf-8", "gbk//IGNORE", $fileName);
    // 清理缓存
    ob_end_clean();
    if ($suffix == 'xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
    } elseif ($suffix == 'xls') {
        header('Content-Type:application/vnd.ms-excel');
        $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
    }
    header('Content-Disposition: attachment;filename="' . $fileName . '.' . $suffix . '"');
    header('Cache-Control: max-age=0');
    $writer = new $class($spreadsheet);
    $writer->save('php://output');
    // 删除清空 释放内存
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
    exit;
}

4. 导出csv文件

/**
 * 导出csv文件
 * @param   string  $fileName   文件名称
 * @param   array   $headArr    Excel标题头数组
 * @param   array   $data       数据内容
 * @return  bool|string
 */
public function exportCsv($fileName = "myData", $headArr = [], $data = [])
{
    @ini_set('memory_limit', '2048M');
    @set_time_limit(0);
    if (!$headArr || !$data || !is_array($data)) {
        return false;
    }
    // 修改csv中的头
    $string   = "";
    foreach ($headArr as $item) {
        // 首先写入表格标题栏
        $string  .= implode(',', $item).",";
    }
    $headArr = explode(",",$string);
    try {
        setlocale(LC_ALL, 'en_US.UTF-8');
        // 输出 Excel 文件头
        $fileName = empty($fileName) ? date('YmdHis') : $fileName . '_' . date('YmdHis');// 文件名称连接上相应的时间戳信息
        $fileName = $fileName . ".csv";
        $string   = "";
        // 首先写入表格标题栏
        $string  .= implode(',', $headArr) . "\n";

        foreach ($data as $datum) { // 循环下查询数据([0=>[0=>[0]]])
            foreach ($datum as $key => $value) {
                foreach ($value as $k => $val) {
                    $value[$k] = $val;
                }
                $string .= implode(",", $value) . "\n"; // 用英文逗号分开
            }
        }

        ob_end_clean();
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $fileName);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo iconv('UTF-8', 'GBK//IGNORE', $string);
        exit;
    } catch (\Exception $e) {
        return $e->getMessage();
    }
}


这篇关于使用 phpSpreadsheet 导出 Excel 完美支持超出26列 和 使用php原生导出 CSV 格式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程