ホームページ  >  記事  >  バックエンド開発  >  phpspreadsheet がデータを Excel にエクスポートする方法の概要 (コード例)

phpspreadsheet がデータを Excel にエクスポートする方法の概要 (コード例)

不言
不言転載
2019-02-13 14:55:016282ブラウズ

この記事では、phpspreadsheet を使用して Excel にデータをエクスポートする方法 (コード例) を紹介します。一定の参考価値があります。必要な友人が参考にすることができます。お役に立てれば幸いです。

PHP を使用して Excel データをエクスポートする前は、PHPExcel ライブラリを使用していましたが、phpoffice は、PHPExcel が廃止され、メンテナンスされなくなったことを公式に発表しました。以下の図に示すように、phpspreadsheet を使用することをお勧めします。

phpspreadsheet がデータを Excel にエクスポートする方法の概要 (コード例)

composer を通じて phpspreadsheet をインストールできます

phpspreadsheet がデータを Excel にエクスポートする方法の概要 (コード例)

composer require phpoffice/phpspreadsheet

phpspreadsheet を使用して生徒情報をブラウザのコード例にエクスポートします

/**
 * 输出到浏览器(需要设置header头)
 * @param string $fileName 文件名
 * @param string $fileType 文件类型
 */
function excelBrowserExport($fileName, $fileType) {

    //文件名称校验
    if(!$fileName) {
        trigger_error('文件名不能为空', E_USER_ERROR);
    }

    //Excel文件类型校验
    $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
    if(!in_array($fileType, $type)) {
        trigger_error('未知文件类型', E_USER_ERROR);
    }

    if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
        header('Cache-Control: max-age=0');
    } else { //Excel5
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
        header('Cache-Control: max-age=0');
    }
}

$data = [
    [1, 'jack', 10],
    [2, 'mike', 12],
    [3, 'jane', 21],
    [4, 'paul', 26],
    [5, 'kitty', 25],
    [6, 'yami', 60],
];

$title = ['id', 'name', 'age'];

$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();

//设置工作表标题名称
$worksheet->setTitle('工作表格1');

//表头
//设置单元格内容
foreach ($title as $key => $value) {
    $worksheet->setCellValueByColumnAndRow($key+1, 1, $value);
}

$row = 2; //从第二行开始
foreach ($data as $item) {
    $column = 1;

    foreach ($item as $value) {
        $worksheet->setCellValueByColumnAndRow($column, $row, $value);
        $column++;
    }
    $row++;
}


$fileName = '学生信息';
$fileType = 'Xlsx';

//1.下载到服务器
//$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
//$writer->save($fileName.'.'.$fileType);

//2.输出到浏览器
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件
excelBrowserExport($fileName, 'Xlsx');
$writer->save('php://output');

エクスポート結果は図のようになります:

phpspreadsheet がデータを Excel にエクスポートする方法の概要 (コード例)

以上がphpspreadsheet がデータを Excel にエクスポートする方法の概要 (コード例)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcnblogs.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。