方式一:使用PHPExcel类库
//引入PHPExcel库文件(路径根据自己情况)
include './phpexcel/Classes/PHPExcel.php';
$excel = new PHPExcel(); //创建对象
$letter = array('A','B','C','D','E','F','F','G'); //Excel表格式,这里简略写了8列
$tableheader = array('学号','姓名','性别','年龄','班级');//表头数组
//填充表头信息
for($i = 0;$i < count($tableheader);$i++) {
$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
}
$data = array(
array('1','小王','男','20','100'),
array('2','小李','男','20','101'),
array('3','小张','女','20','102'),
array('4','小赵','女','20','103')
);
//填充表格信息
for ($i = 2;$i <= count($data) + 1;$i++) {
$j = 0;
foreach ($data[$i - 2] as $key=>$value) {
$excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
$j++;
}
}
$write = new PHPExcel_Writer_Excel5($excel);
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="testdata.xls"');
header("Content-Transfer-Encoding:binary");
$write->save('php://output');
方式二:简单的PHP导出excel,不适用任何外部类库文件
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=reply.csv");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
$header = array('学号','姓名','性别','年龄','班级');
$converter = function($value) {
return iconv('utf-8', 'gbk', $value);
};
$header = array_map($converter, $header);
$list = array(
array('1','小王','男','20','100'),
array('2','小李','男','20','101'),
array('3','小张','女','20','102'),
array('4','小赵','女','20','103')
);
fputcsv($output, $header);
foreach($list as $k => $v)
{
$csvrow = array_map($converter, array(
$v[0],
$v[1],
$v[2],
$v[3],
$v[4],
));
fputcsv($output, $csvrow);
}
fclose($output);