PHP生成Excel文件

客官,留下你的赞;成为我的粉丝,一起上车哦!评论区欢迎你的留言

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
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值