源码的excel导入导出

       获取所有数据,将数据进行有序切割,在进行遍历,将其导出。

//设置header
   header("content-type:text/html;charset=utf-8");
   //连接数据库
   $link=mysqli_connect("localhost:3306","root","root","student");
   //设置字符集
   mysqli_query($link,"set names utf8");
   //查询所有数据遍历数来
   $sql="select * from users";
   $res=mysqli_query($link,$sql);
   while($row=mysqli_fetch_assoc($res)){
       $data[]=$row;
   }
   //php防乱码
   $str=iconv("utf-8","gb2312","ID\t名字\t密码"."\n");
   //遍历数据
   foreach($data as $key=>$v){
       //php防乱码
       $str.=iconv("utf-8","gb2312",$v['id']."\t".$v['name']."\t".$v['password']."\n");
   }
   //输出
   header("content-type:application/vnd.ms-excel");
   header("content-disposition:attachment;filename=users.xls");
   echo $str;

        导入时,先在数据库中建立数据表。获取文件内容,将其切割成数组,进行有序分割,遍历导入数据库。

//设置表头
header("Content-type:text/html;charset=UTF-8");
//从文件里面读取内容
$str=trim(file_get_contents("users.xls"));
//切割字符串转化成数组
$data=explode("\n",$str);
//遍历字符串将其转化成数组
foreach($data as $key=>$v){
    $arr[]=explode("\t",$v);
    unset($arr[0]);
};
//连接数据库
$link=mysqli_connect("localhost","root",'root',"student");
//设置字符集
if (!$link){
    echo "连接错误";
}
//定义一个空的sql语句
$sql='';
//将数据入库
foreach($arr as $v){
    //php防乱码
    $aa=iconv("gb2312","utf-8","('$v[0]','$v[1]','$v[2]')");
    //添加数据入库
    $sql="insert into users (id,name,password) values ".$aa;
    $a=mysqli_query($link,$sql);
}
if ($a){
    echo "添加成功";
}

猜你喜欢

转载自www.cnblogs.com/yingyong/p/9973212.html