首先使用composer安装xlsxwriter,示例如下:
composer create-project mk-j/php_xlsxwriter
// 或者
composer require mk-j/php_xlsxwriter
安装完成之后就可以使用了,下面是简单的使用示例:
$title = ['昵称','头像','手机号','日期'];//设置头
$sheet1 = 'sheet1';//设置工作簿名称
$writer = new \XLSXWriter();
$styles1 = array( 'font'=>'宋体','font-size'=>10,'font-style'=>'bold', 'fill'=>'#eee',
'halign'=>'center', 'border'=>'left,right,top,bottom');//设置样式
$writer->writeSheetRow($sheet1, $title,$styles1);//写入头
$styles2 = ['height'=>16];//单独设置头的样式
//遍历数据
foreach($data as $row){
$writer->writeSheetRow($sheet1,[$row['nickname'],$row['head_img'],$row['tel'],$row['add_time']],$styles2);//写入数据
}
//设置 header,用于浏览器下载
$filename = "members.xlsx";//下载名
header('Content-disposition: attachment; filename="'.\XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$writer->writeToStdOut();die;//输出