PHP將mysql數據導出爲Excel

項目需要,由於系統工作日誌數據量很大,所以定期將歷史日誌導出爲Excel。


功能目錄:

root@bupt925:/home/bupt/xuxueliang/OutputExcel# ll
total 24
drwxr-xr-x 6 root root 4096 10月 16 10:46 ./
d-wx-wx--x 9 1000 bupt 4096 10月 16 10:38 ../
drwxr-xr-x 2 root root 4096 10月 16 10:46 bin/
drwxr-xr-x 2 root root 4096 10月 16 10:36 conf/
drwxr-xr-x 2 root root 4096 10月 16 10:46 data/
drwxr-xr-x 2 root root 4096 10月 16 10:33 log/


功能代碼:

<?php
    /*
        Date:2013-10-16
        author:xxl
        function:對歷史日誌導出爲excel文件
    */
    include '../conf/connect_mysql.php';
    include '../conf/conf.php';
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: p_w_upload;filename="user.csv"');
    header('Cache-Control: max-age=0');
    $fiveago =  mktime(date("H"),date("i"),date("s"),date("m")-1,date("d"),date("Y"));
    $date = date("Y-m-d",$fiveago);
    $sql = "select * from Record_Log where date<'$date'";
    $sqlf = mysql_query($sql);
    $file_name = "../data/Log_".$date.".csv";
    $fp = fopen($file_name,'a');
    $head = array('ID','用戶名','時間','類型','井場名','工作內容','回執內容');
    foreach($head as $i=>$v)
    {
        $head[$i] = iconv('utf-8','gbk',$v);
    }
    fputcsv($fp,$head);
    $cnt = 0;
    $limit = 100000;
    while(($info = mysql_fetch_array($sqlf,MYSQL_NUM)))
    {
        $cnt ++ ;
        if($cnt == $limit)
        {
            $cnt = 0;
            ob_flush();
            flush();
        }
        foreach($info as $i=>$v)
        {
            $info[$i] = iconv('utf-8','gbk',$v);
        }
        fputcsv($fp,$info);
    }
    if($ifdelete)
    {
        $sql = "delete from Record_Log where date<'$date'";
        $sqlf = mysql_query($sql);
        if($sqlf)
            echo "Delete Success.\n";
        else
            echo "Delete Error.\n";
    }
    echo "Done\n";
?>


生成的csv文件:

root@bupt925:/home/bupt/xuxueliang/OutputExcel/data# ll
total 12
drwxr-xr-x 2 root root 4096 10月 16 10:47 ./
drwxr-xr-x 6 root root 4096 10月 16 10:46 ../
-rw-r--r-- 1 root root 5564 10月 16 10:47 Log_2013-09-16.csv


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章