<?php

/**
 * 导出table格式的excel
 * 所有数据都是直接输出有利于内存释放
 * @Author: luffy丶大叔
 * @Z 2015-5-11 13:58:32
 * @email luffy00789@126.com
 * @encoding UTF-8
 */
class Common_ExportExcelByTable{

    /**
     * 文本型
     */
    const CELL_TEXT_TYPE = "@";

    /**
     * 日期格式
     */
    const CELL_DATE_TYPE = "yyyy/mm/dd";

    /**
     * 浮点2位小数
     */
    const CELL_FLOAT_TYPE = "#,##0.0000";
    /**
     * 数值型
     */
    const CELL_NUMERICAL_TYPE = "#,##0";

    /**
     * 货币
     */
    const CELL_CURRENCY_TYPE = "￥#,##0.00";

    /**
     * 百分比
     */
    const CELL_PERCENT_TYPE = "#0.00%";
    private $fileSource;
    private $file;
    public $rule;
    /**
     * 构造函数
     * 用来输出table头的
     */
    public function __construct($filename,$mod='wb+')
    {
      $this->fileSource=fopen($filename,$mod);
      $this->file=$filename;
    }
    public function writeString($string){
        fwrite($this->fileSource,$string);
    }
    public function writeRow($row){
        foreach($row as $r){
            $this->writeString($r);
        }
    }
    public function writeOneTr($row){
         $this->writeString("<tr style='border:1px solid #ddd;'");
        foreach($row as $k=>$v){
            $style=$this->rule[$k];
            $this->writeString('<td '.$style.'>'.$v.'</td>');
        }
      $this->writeString("</tr>");
    }
    public function setTexRule($rule){
        foreach($rule as $col){
            $this->rule[$col]=" style='vnd.ms-excel.numberformat:@'";
        }   
       }
    public static function combineFile($file,$targetFile){
        $out=false;
        $shell='cat';
        if(is_string($file)){
            $shell.=$file;
        }elseif (is_array($file)) {
            foreach($file as $f){
                $shell.=' '.$f;
            }
        }else{
            return false;
        }
        $shell.=' >'.$targetFile;
        exec($shell,$out);
        return $out;
    }
    public function downLoadExcelFile($downloadName){
        header('Content-Type: application/vnd.ms-excel;charset=gbk');
        header("Content-Disposition: attachment;filename={$downloadName}");
        header('Cache-Control: max-age=0');
         $file_size=filesize($this->file);
        $buffer     = 8192;
        $file_count = 0;
        while (!feof($this->fileSource) && $file_count < $file_size) {
            $file_con = fread($this->fileSource, $buffer);
            $file_count += $buffer;
            echo $file_con;
            ob_flush();
            flush();
        }
    }
    /**
     * 析构函数
     * 用来输出 /table
     */
    public function __destruct()
    {
        fclose($this->fileSource);
    }
}
