php 导出方法


    /**
     * Excel导出
     *
     * @param array $title
     * @param array $data
     * @param string $filename
     * @param string $sheet_name
     */
    public function exportExcel($title = array(),$data = array(),$filename = null, $sheet_name = '')
    {
        $sheet_name = empty(!$sheet_name)?mb_convert_encoding($sheet_name,"GBK", "UTF-8"):'';
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
            xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
            <head>
            <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
            <meta http-equiv=Content-Type content="text/html; charset=GBK">
            <!--[if gte mso 9]><xml>
            <x:ExcelWorkbook>
            <x:ExcelWorksheets>
            <x:ExcelWorksheet>
            <x:Name>'.$sheet_name.'</x:Name>
            <x:WorksheetOptions>
            <x:DisplayGridlines/>
            </x:WorksheetOptions>
            </x:ExcelWorksheet>
            </x:ExcelWorksheets>
            </x:ExcelWorkbook>
            </xml><![endif]--></head><table>
            <tbody>';


        if (false !== $index = array_search('色号', $title)) {
            unset($title[$index]);
            $title = array_values($title);
        }

        // 写入表头
        if (!empty($title)){
            foreach ($title as $k => $v) {
                // 设定文本格式
                $title[$k]="<td style='vnd.ms-excel.numberformat:@'>".mb_convert_encoding($v,"GBK", "UTF-8")."</td>";
            }
            $title= "<tr>".implode("\t", $title)."</tr>";
            echo "$title\n";
        }

        // 写入数据内容
        if (!empty($data)){
            foreach($data as $key=>$val){
                unset($val['color_id']);
                foreach ($val as $ck => $cv) {
                    // 设定文本格式
                    $data[$key][$ck]="<td style='vnd.ms-excel.numberformat:@'>".mb_convert_encoding($cv,"GBK", "UTF-8")."</td>";
                }
                $data[$key]="<tr>".implode("\t", $data[$key])."</tr>\n";
            }

            echo implode("\n",$data);
        }

        echo '</tbody></table>';

        exit();
    }

    /**
     * 导出csv
     *
     * @param array $head 标题
     * @param array $data 数据
     * @param string $filename 文件名
     * @return void
     */
    function exportCsv($head, $data, $filename)
    {
        // 输出Excel文件头,可把user.csv换成你要的文件名
        header('Content-Type: application/octet-stream');
        header('Accept-Ranges:bytes');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
        header('Cache-Control: max-age=0');

        // 打开PHP文件句柄,php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        // 输出Excel列名信息
        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码,一定要转换,否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v)."\t";
        }

        // 将数据通过fputcsv写到文件句柄
        fputcsv($fp, $head);

        // 计数器
        $cnt = 0;
        // 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
        $limit = 100000;

        // 逐行取出数据,不浪费内存
        $count = count($data);
        for($t=0;$t<$count;$t++) {

            $cnt ++;
            if ($limit == $cnt) { //刷新一下输出buffer,防止由于数据过多造成问题
                ob_flush();
                flush();
                $cnt = 0;
            }
            $row = $data[$t];
            foreach ($row as $i => $v) {
                $row[$i] = iconv('utf-8', 'gbk', $v);
            }
            fputcsv($fp, $row);
        }
        fclose($fp);
        exit();
    }

    /**
     * csv文件导入
     *
     * @param string $file
     * @return [$title, $data]
     */
    public function import_csv($file = null)
    {
        $handle = fopen($file, 'r');

        $out = array();
        $n = 0;
        while ($data = fgetcsv($handle, 10000)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                $out[$n][$i] =  mb_convert_encoding(trim($data[$i]), "UTF-8", "GBK");
            }
            $n++;
        }

        // 获取表单头信息
        $title = array_filter(array_shift($out));

        // 去除整行为空的值,保留键值
        $data = array_filter($out, function($v) {
            // 去除空格
            foreach ($v as &$value) {
                $value = preg_replace("/\s/","",$value);
            }
            unset($value);
            if (!empty(array_filter($v))) {
                return true;
            }
            return false;
        });

        return [$title, $data];
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值