>  기사  >  php教程  >  excel导出

excel导出

PHP中文网
PHP中文网원래의
2016-05-23 16:40:591077검색

<?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);
?>

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.