使用PHP导入和导出CSV文件

1.配置文件:connect.php

<?php
$host="localhost";
$db_user="root";
$db_pass="root";
$db_name="wh";
$timezone="Asia/Shanghai";

$link=mysql_connect($host,$db_user,$db_pass);
mysql_select_db($db_name,$link);
mysql_query("SET names UTF8");

header("Content-Type: text/html; charset=utf-8");
?>

2.页面:index.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>使用PHP导入和导出数据为CSV文件</title>
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<style type="text/css">
.demo{width:400px; height:100px; margin:100px auto}
.demo p{line-height:32px}
.btn{width:80px; height:26px; line-height:26px; background:url(btn_bg.gif) repeat-x; border:1px solid #ddd; cursor:pointer}
</style>
</head>

<body>
<div id="header">
    
</div>

<div id="main">
   
  <div class="demo">
      <form id="addform" action="do.php?action=import" method="post" enctype="multipart/form-data">
         <p>请选择要导入的CSV文件:<br/><input type="file" name="file"> <input type="submit" class="btn" value="导入CSV">
         <input type="button" class="btn" id="exportCSV" value="导出CSV" onClick="window.location.href='do.php?action=export'"></p>
      </form>
  </div>
</div>
<div id="footer">
     
</div>
<p id="stat"><script type="text/javascript" src="http://js.tongji.linezing.com/1870888/tongji.js"></script></p>
</body>
</html>

3.逻辑页面:do.php

<?php

/**
 * @
 * @Description:
 * @Copyright (C) 2011 helloweba.com,All Rights Reserved.
 * -----------------------------------------------------------------------------
 * @author: Liurenfei (lrfbeyond@163.com)
 * @Create: 2012-5-1
 * @Modify:
*/
include_once ("connect.php");

$action = $_GET['action'];
if ($action == 'import') { //导入CSV
    $filename = $_FILES['file']['tmp_name'];
    if (empty ($filename)) {
        echo '请选择要导入的CSV文件!';
        exit;
    }

    // echo $filename;
    // echo '<br/>';
    $handle = fopen($filename, 'r');
    // $handle = fopen('aaaa.csv', 'r');
    $result = input_csv($handle); //解析csv


    $len_result = count($result);
    if($len_result==0){
        echo '没有任何数据!';
        exit;
    }
    // var_dump($result);
    // var_dump($len_result);
    // exit;
    for ($i = 0; $i < $len_result; $i++) { //循环获取各字段值
        $name = iconv('gb2312', 'utf-8', $result[$i][0]); //中文转码
        $sex = iconv('gb2312', 'utf-8', $result[$i][1]);
        // $age = $result[$i][2];
        // $data_values .= "('$name','$sex','$age'),";
        $data_values .= "('$name','$sex'),";
    }
    $data_values = substr($data_values,0,-1); //去掉最后一个逗号
    fclose($handle); //关闭指针
    $query = mysql_query("insert into bb (uniprot,url) values $data_values");//批量插入数据表中
    if($query){
        echo '导入成功!';
    }else{
        echo '导入失败!';
    }
} elseif ($action=='export') { //导出CSV
    $result = mysql_query("select * from aa");
    $str = "id,uniprot,url\n";
    $str = iconv('utf-8','gb2312',$str);
    while($row=mysql_fetch_array($result)){
        $name = iconv('utf-8','gb2312',$row['id']);
        $sex = iconv('utf-8','gb2312',$row['uniprot']);
        $str .= $name.",".$sex.",".$row['url']."\n";
    }
    $filename = date('Ymd').'.csv';
    export_csv($filename,$str);
}
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;
}

function export_csv($filename,$data) {
    header("Content-type:text/csv");
    header("Content-Disposition:attachment;filename=".$filename);
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    echo $data;
}
?>

 

posted @ 2016-01-31 09:41  侠岚之弋痕夕  阅读(5561)  评论(0编辑  收藏  举报
Where is the starting point, we don't have a choice, but the destination where we can pursue!