首頁 > php教程 > PHP源码 > 主體

excel导出

PHP中文网
發布: 2016-05-23 16:40:59
原創
1074 人瀏覽過

<?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
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板