首页 > php教程 > PHP源码 > excel导出

excel导出

PHP中文网
发布: 2016-05-23 16:40:59
原创
1095 人浏览过

<?php
/**
 * @author Jceee
 */
class excel_tool
{
    public static $readerObj;
    public static $charset = &#39;utf-8&#39;;
 
	/**
	 * 输出切换编码
	 */
	public static function excelExportIconv($output){

		return iconv(self::$charset, &#39;GBK&#39;, $output);
	}

    /**
     * 导出文件
     * @param $fileName  string  
     * @param $title     string
     * @param $firstRow  array       
     *          如:array(&#39;name&#39;=>&#39;名字&#39;, &#39;title&#39; => &#39;标题&#39;) 键名与后面的数组$data的子元素键名关联
     * @param $data      array
     */
	public static function exportFile($fileName, $title = &#39;&#39;, $firstRow = array(), $data = array())
	{
		header(&#39;Content-Type: application/vnd.ms-execl&#39;);
		header(&#39;Content-Disposition: attachment; filename=&#39; . $fileName . &#39;.xls&#39;);
		header(&#39;Pragma: no-cache&#39;);
		header(&#39;Expires: 0&#39;);

        if (!empty($title)) {
			echo self::excelExportIconv($title) . "\t\n";
        }

        /**
         *  第一行与后面的数据以键名关联
         */
		if (!empty($firstRow) && is_array($firstRow)) {

			//输出第一行内容
			foreach ($firstRow as $first) {
				echo self::excelExportIconv($first) . "\t";
			}
			echo "\n";

			if (!empty($data) && is_array($data)) {
				foreach ($data as $item) {
					foreach ($firstRow as $_key => $_val) {
						if (isset($item[$_key])) {
							echo self::excelExportIconv($item[$_key]) . "\t";
						} else {
							echo self::excelExportIconv(&#39;&#39;) . "\t";
						}
					}
					echo "\n";
				}
			}
		} else {

			if (!empty($data) && is_array($data)) {
				foreach ($data as $item) {
					foreach ($item as $val) {
						echo self::excelExportIconv($val) . "\t";
					}
					echo "\n";
				}
				echo "\n";
			}
		}

	}
}


/**
 * example:
 */
$fileName = &#39;example&#39;;
$title = &#39;This is title&#39;;
$firstRow = array(
  &#39;id&#39; => &#39;ID&#39;,
  &#39;name&#39; => &#39;名字&#39;,
  &#39;title&#39; => &#39;标题&#39;
  );
$data = array(
  array(&#39;id&#39; => 1, &#39;name&#39; => &#39;名字1&#39;, &#39;title&#39; => &#39;标题1&#39;),
  array(&#39;id&#39; => 2, &#39;name&#39; => &#39;名字2&#39;, &#39;title&#39; => &#39;标题2&#39;),
  array(&#39;id&#39; => 3, &#39;name&#39; => &#39;名字3&#39;, &#39;title&#39; => &#39;标题3&#39;),
  array(&#39;id&#39; => 4, &#39;name&#39; => &#39;名字4&#39;, &#39;title&#39; => &#39;标题4&#39;),
  );
Excel_tool::exportFile($fileName,$title,$firstRow,$data);
?>
登录后复制

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板