客官,留下你的赞;成为我的粉丝,一起上车哦!评论区欢迎你的留言
PHP生成Excle
<?php
/**
* PHP7 实现Excle下载
* @link https://github.com/Echo-Mr-Pengw
* @author new1024kb
* @since 2020-01-03
*/
/**
* [downloadExcel 下载Excel方法]
* @param [array] $data [二维数组]
* @param [string] $excleTitle [Excle内部的标题]
* @param [string] $fileName [Excle文件名]
* @return [type] [description]
*/
function downloadExcel($data, $excleTitle = 'Excel表格', $fileName = 'excle') {
//数据为空或者不是数据,返回false
if(!$data || !is_array($data)) {
return false;
}
$str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
$str .= '<table><head> ' . $excleTitle. '</head>';
$str .= '<tr><th>标题1</th></tr>'; //标题 第一行第一列
foreach($data as $v1) {
$str .= '<tr>';
foreach($v1 as $v2) {
$str .= '<td>' . $v2 .'</td>';
}
$str .= "</tr>\n";
}
$str .= '</table></head></body>';
//告诉浏览器,导出Excle
header( "Content-Type: application/vnd.ms-excel; name='excel'" );
//以流的形式下载文件,这样可以实现任意格式的文件下载
header( "Content-type: application/octet-stream" );
//将其保存为一个文件,命名为xxx.xls
header( "Content-Disposition: attachment; filename=" . $fileName .".xls");
//强制页面不缓存
header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
//每次使用缓存时,都会像服务器进行验证,如果缓存更新了,返回最新的;否则,返回304,使用本地缓存
header( "Pragma: no-cache" );
header( "Expires: 0" );
//输出并终止
exit($str);
}
$data = [
['第二行第一列'] //注意:这里需要跟第25行代码(标题)对应。
//['第二行第一列', '第二行第二列']
//第25行代码需要修改成 $str .= '<tr><th>标题1</th><th>标题2</th></tr>';
];
downloadExcel($data);
在浏览器里面访问,会自动下载excle.xls
打开excle.xls