Can
Be Better

PhpSpreadsheet 使用心得

1.自动换行与自适应行宽

$spreadsheet = new Spreadsheet();
$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

foreach ($cellName as $name) {
    $spreadsheet->getActiveSheet()->getColumnDimension($name)->setAutoSize(true);
    $spreadsheet->getActiveSheet()->getStyle($name)->getAlignment()->setWrapText(true);
}

2.IE以及Edge下载文件乱码

        $ua = $_SERVER['HTTP_USER_AGENT'];
        $ua = strtolower($ua);
        if(preg_match('/msie/', $ua) || preg_match('/edge/', $ua)) { //判断是否为IE或Edge浏览器
            $fileName = str_replace('+', '%20', urlencode($fileName)); //使用urlencode对文件名进行重新编码
        }

3.header设置

header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

4.输出文件

        $spreadsheet->getActiveSheet()->fromArray($arrayData, NULL);

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        ob_end_clean(); //清除缓冲区,避免乱码
        $writer->save("php://output");

不开启评论,如有问题疑问请发邮件。[email protected]最长的路 » PhpSpreadsheet 使用心得