zoukankan      html  css  js  c++  java
  • CSV文件导入数据库和导出数据库

    实例一:

    <?php
    $filename = 'test';
    //导出文件
    header("Content-type: application/vnd.ms-excel; charset=utf-8");
    Header("Content-Disposition: attachment; filename=".$filename.".csv");

    echo "商品名称,商品编号,商品价格,商品品牌,商品颜色 ";

    $arr = [
    ['貂秋1','dq00001','1000','雕牌','红色'],
    ['貂秋2','dq00002','1000','雕牌','蓝色'],
    ['貂秋3','dq00003','1000','雕牌','绿色'],
    ['貂秋4','dq00004','1000','雕牌','白色']
    ];
    //将数组循环遍历并输出
    foreach ($arr as $item){
    echo implode(',',$item)." ";
    }

    示例二:

    //从数据库中导出

    $conn = mysqli_connect('localhost','root','123456','st0614');//连接数据库

    $filename = 'student';//文件名为student
    header("Content-type: application/vnd.ms-excel; charset=utf-8");
    Header("Content-Disposition: attachment; filename=".$filename.".csv");

    $res = mysqli_query($conn,'select * from student');
    echo "ID,姓名,性别,年龄,院系,班级,头像 ";//表头
    while($row = mysqli_fetch_assoc($res))//获取数据库数据
    {
    $arr[] = $row;
    }
    foreach ($arr as $item){
    echo implode(',',$item)." ";//输出
    }

    //SVN导入数据库

    $file = 'text.txt';
    if (isset($_POST['commit'])){
    $file = $_FILES['csv'];
    $fileName=$file['tmp_name'];

    $fp = fopen($fileName,'r');
    $i=0;
    while ($file_data = fgetcsv($fp))
    {
    $i++;
    if($i==1)
    {
    continue;//过滤表头
    }else{
    $data[$i] = $file_data;
    }

    }
    fclose($fp);
    }

    <-- ---------请分开--------- -->
    //存入数据库
    if (isset($data)){
    foreach ($data as $item){
       $name = iconv('gb2312','utf-8',$item[1]);
       $sql = "insert into student(`name`,`sex`,`age`,`d_id`,`class_id`,`tumble`) values('{$name}',{$item[2]},{$item[3]},{$item[4]},{$item[5]},'{$item[6]}')";
       $res = mysqli_query($conn,$sql);
    }
     if ($res){
       echo '上传成功!';
     }else{
       echo '上传失败!';
     }
    }

    ?>
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport"
    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    </head>
    <body>

    <form action="" method="post" enctype="multipart/form-data">
    csv文件:
    <input type="file"name="csv">
    <--<button id="btn" onclick="<?php //download(); ?>">下载</button>-->
    <input type="submit" name="commit" value="上传">
    </form>

    </body>
    </html>

  • 相关阅读:
    关于虚拟机断电导致的 generating /run/initramfs/rdsosreport.txt 问题优秀解决方案
    centos7 yum 阿里源
    startup.bat脚本启动tomcat时,cmd命令窗口闪现问题及Neither the JAVA_HOME nor the JRE_HOME environment variable is defined 错误解决
    Linux 中 Fish Shell
    卸载mysql
    /bin/bash^M: 坏的解释器: 没有那个文件或目录
    elementUI 文本鼠标移入显示太长
    el-upload 手动上传文件
    vue-element-admin 打包测试环境报错
    vue 分页跳转页面详情,返回记住当前点击第几页
  • 原文地址:https://www.cnblogs.com/yinfa/p/11267198.html
Copyright © 2011-2022 走看看