Heim  >  Artikel  >  Backend-Entwicklung  >  PHP导入导出EXCELl,CSV

PHP导入导出EXCELl,CSV

WBOY
WBOYOriginal
2016-06-23 13:12:29882Durchsuche

## PHP导入导出Excel,CSV## HTML```<form action="{:U('Admin/Unit/importcsv')}" method="post" name="myform" id="myform" enctype="multipart/form-data">    <input type="hidden" name="unit_id" value="{$unit_id}"/>    <h3 style="background:#006699; color:#FFFFFF; width:450px;">{$unit.1.1.num}号楼/{$unit.1.1.unit}单元</h3>    <p>        请选择要导入的CSV文件:        <br/>        <input type="file" name="file">        <input type="submit" name="dosubmit" id="dosubmit" class="dialog btn btn-primary" value="导入CSV">        <input class="btn btn-default" type="button" onclick="javascript:history.back(-1);" value="{:L('GOBACK')}" >        <!-- <input type="button" class="btn" value="导出CSV" onclick="window.location.href='do.php?action=export'"> -->    </p></form>```### PHP 导入> function importcsv```/**     * [importcsv description]     * @return [type] [description]     */    public function importcsv() {        if (IS_POST) {            $filename = $_FILES['file']['tmp_name'];            if (empty($filename)) {                $this->error("csv导入文件请不要为空");            }            $handle = fopen($filename, 'r');            function input_csv($handle) {                $out = array();                $n = 0;                while ($data = fgetcsv($handle, 10000)) {                    $num = count($data);                    for ($i = 0; $i < $num; $i++) {                        $out[$n][$i] = $data[$i];                    }                    $n++;                }                return $out;            }            $result = input_csv($handle); //解析csv            //$number = count($result, COUNT_RECURSIVE) - count($result);            // $len_result = count($result);            $len_result = count($result) - 1;            if ($len_result == 0) {                $this->error("csv导入数据为空");            }            foreach ($result as $kr => $vr) {            //这里写你的业务逻辑                if ($kr) {                    $i = 0;                    //中文转码                    $data['estate_id'] = iconv('gb2312', 'utf-8', $vr[$i++]); //楼盘ID                    $data['num'] = iconv('gb2312', 'utf-8', $vr[$i++]); //楼栋                    $data['unit'] = iconv('gb2312', 'utf-8', $vr[$i++]); //单元                    $data['floors'] = iconv('gb2312', 'utf-8', $vr[$i++]); //楼层                    $data['number'] = iconv('gb2312', 'utf-8', $vr[$i++]); //门牌号                    $data['status'] = iconv('gb2312', 'utf-8', $vr[$i++]); //状态                    $data['type'] = iconv('gb2312', 'utf-8', $vr[$i++]); //关联户型                    $data['market_money'] = iconv('gb2312', 'utf-8', $vr[$i++]); //市场价                    //create_time last_time NOW_TIME                    $data['create_time'] = iconv('gb2312', 'utf-8', NOW_TIME); //创建时间                    $data['last_time'] = iconv('gb2312', 'utf-8', NOW_TIME); //修改时间                    $list = D('Property')->add($data);                }            }            if ($list) {                $unit_info = D('Unit')->where('id=' . I('unit_id'))->find();                $map['estate_id'] = $unit_info['estate_id'];                $map['building'] = $unit_info['building'];                $buildid = D('Building')->where($map)->getField('id');                $success = D('Unit')->where('id=' . I('unit_id'))->data(array('status' => 1))->save();                if ($success) {                    $this->success("csv导入成功!共导入" . $len_result . "条数据", U('Admin/Unit/index', array('id' => $buildid)));                }            } else {                $this->error("csv导入失败!");            }            fclose($handle); //关闭指针        } else {            $info = M('Unit')->where('id=' . I('id'))->find();            $buid = D('Property')->bulid_property($info);            S('buid' . time() . I('id'), $buid);            $protype = D('Estate')->get_project_type($info['estate_id']);            $this->assign('unit', $buid);            $this->assign('unit_id', I('id'));            $this->assign('protype', $protype);            $this->assign('estate_id', 'buid' . time() . I('id'));            $this->display();        }    }```### PHP 导出> 这里本来想导出Excel,先导出成csv了,具体的大家可以按自己的意愿更改> function exportcsv```    /**     * [exportcsv description]导出Excel     * @return [type] [description]     */    public function exportcsv() {        //导出Excel     estate_id num unit        $id = I('id');        if (isset($id) && !empty($id)) {            $unit_info = D('Unit')->where('id=' . $id)->find();            if ($unit_info) {                $map = array();                $map['estate_id'] = $unit_info['estate_id']; //楼盘ID                $map['num'] = $unit_info['building']; //楼栋                $map['unit'] = $unit_info['unit']; //单元                $result = M('property')->where($map)->select();                if ($result) {                    $title = array('序列', '项目#楼盘', '楼栋', '单元', '楼层', '门牌号', '状态', '关联户型', '市场价', '创建时间', '修改时间');                    foreach ($result as $k => $v) {                        $data[$k][] = $v['id']; //序列                        $data[$k][] = idtoname($v['estate_id'], 'Estate', 'name', 'id') . '#' . $v['estate_id']; //项目#楼盘                        $data[$k][] = $v['num']; //楼栋                        $data[$k][] = $v['unit']; //单元                        $data[$k][] = $v['floors']; //楼层                        $data[$k][] = $v['floors'] . '0' . $v['number']; //门牌号                        $data[$k][] = $v['status']; //状态                        $data[$k][] = idtoname($v['type'], 'ProType', 'name', 'id'); //关联户型                        $data[$k][] = format_price($v['market_money']); //市场价                        $data[$k][] = time_format($v['create_time']); //创建时间                        $data[$k][] = time_format($v['last_time']); //修改时间                    }                    export_csv_xls($title, $data);                    unset($title, $data);exit;                }            } else {                $this->error("未查询到楼盘单元信息!");            }        } else {            $this->error("csv导入失败!");        }    }```> function export_csv_xls```function export_csv_xls($title, $array = '', $code = 'gb2312', $filename = "") {    if (!$filename) {        // $filename = date("Y-m-d") . ".xls";        $filename = randStr(10) . ".xls";    }    header("Content-Type: application/vnd.ms-execl");    header("Content-Type: application/vnd.ms-excel; charset=" . $code);    header("Content-Disposition: attachment; filename=$filename");    header("Pragma: no-cache");    header("Expires: 0");    if ($code == "gb2312") {        $title = array_map("utf8togb2312", $title);    }    echo implode("\t", $title) . "\n";    if ($array) {        foreach ($array as $v) {            if ($code == "gb2312") {                $v = array_map("utf8togb2312", $v);            }            echo implode("\t", $v) . "\n";        }    }}```> function utf8togb2312```function utf8togb2312($str) {//编码转换    $str = format_xml_num($str);    $bianma = mb_detect_encoding($str);    if ($bianma == "GB2312") {        return $str;    } else {        return iconv($bianma, 'GB2312', trim($str));    }}```> function format_xml_num```function format_xml_num($str) {//导出格式化数字    if (strlen((float) $str) >= 12 && is_numeric((float) $str) && (float) $str && !strpos($str, '.')) {        $str = "'" . (string) $str;    }    return $str;}```

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn