博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP 导出csv
阅读量:4960 次
发布时间:2019-06-12

本文共 4560 字,大约阅读时间需要 15 分钟。

1. 导入

方法一:

public function actionImport()

{

  $result = array('status' => SUCCESS, 'message' => '');
  $extension = strtolower(end(explode('.', $_FILES['file']['name'])));
  $allowedExts = array('csv');

  if (in_array($extension, $allowedExts))

  {
    if ($_FILES["file"]["error"] > 0)
    {
      $result['status'] = FAIL;
      $result['message'] = $_FILES["file"]["error"];
    }
    else
    {
      $file = fopen($_FILES['file']['tmp_name'], 'r');
      $response = $this->checkCSVError($file);

      if ($response['result']['status'] === SUCCESS)

      {
        $calcResult = $this->getImportedData($response['file']);
        if ($calcResult['status'] === SUCCESS)
        {
          $result['originalData'] = $response['file'];
          $result['newData'] = $calcResult['data'];
        }
        else
        {
          $result['status'] = FAIL;
          $result['message'] = $calcResult['message'];
        }
      }
      else
      {
        $result = $response['result'];
      }
    }
  }
  else
  {
    $result['status'] = FAIL;
    $result['message'] = 'Please select a csv file.';
  }

  echo CJSON::encode($result);

}
private function checkCSVError($file)
{
  $row = -1;
  $result = array('status' => FAIL, 'message' => '');
  $fileData = array();
  $errorLine = array();
  $response = array('result' => '', 'file' => '');

  while ($data = fgetcsv($file))

  {
    $row++;
    if ($row === 0)
    {
      $roleIndex = array_search('role', $data);
      $nameIndex = array_search('name', $data);
      $emailIndex = array_search('email', $data);

      if (!$roleIndex || !$nameIndex || !$emailIndex)

      {
        $result['message'] = 'The data is lack.';
        $response['result'] = $result;

        return $response;

      }
    }

    if (current($data) === null)

    {
      continue;
    }

    $role = $data[$roleIndex];

    $name = $data[$nameIndex];
    $email = $data[$emailIndex];

    if (!empty($role) && !empty($name) && !empty($email))

    {
      $fileData[] = array('role' => $role, 'name' => $name, 'email' => $email);
    }
    else
    {
      $errorLine[] = ($row + 1);
    }
  }

  if ((count($errorLine) === 0) && !empty($fileData))

  {
    $result['status'] = SUCCESS;
    $response['result'] = $result;
    $response['file'] = $fileData;
  }
  else
  {
    $result['message'] = 'The line ' . join(', ',$errorLine) . ' has error. Please check.';
    $response['result'] = $result;
  }
  fclose($file);

  return $response;

}

private function getImportedData($file)

{
  $result = array('status' => SUCCESS, 'message' => '');
  foreach ($file as $row => $value)
  {
    $user = {["role"]=>$value['role'],["name"]=>$value['name'],["email"]=>$value['email']};
    $result['data'][$user['email']] = $user;
  }
  $result['data'] = array_values($result['data']);

  return $result;

}

方法二:

public function actionImport() { //导入CSV $filename = $_FILES['file']['tmp_name']; if (empty ($filename)) { echo '请选择要导入的CSV文件!'; exit; } $handle = fopen($filename, 'r'); $result = $this->input_csv($handle); //解析csv $len_result = count($result); if($len_result==0){ echo '没有任何数据!'; exit; } for ($i = 1; $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 = substr($data_values,0,-1); //去掉最后一个逗号 fclose($handle); //关闭指针 $query = mysql_query("insert into student (name,sex,age) values $data_values");//批量插入数据表中 if($query){ echo '导入成功!'; }else{ echo '导入失败!'; } }
private 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; }

2. 导出

$filename = 'file' . date('mdY') . ".csv";

$data = 'role,name,email' . "\n";

$items = [{["role"]=>'管理员',["name"]=>'小明',["email"]=>'xiaoming@163.com'},{["role"]=>'操作员',["name"]=>'小红',["email"]=>'xiaohong@163.com'},{["role"]=>'用户',["name"]=>'小刚',["email"]=>'xiaogang@163.com'}]

foreach ($items as $user)

{
  $data .=$user['role'] . ',' . str_replace(',', ' ', $user['name']) . ',' . str_replace(',', ' ', $user['email']) . "\n";
}

public function actionExportcsv($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;
}

转载于:https://www.cnblogs.com/floraCnblogs/p/php-import-or-export.html

你可能感兴趣的文章
Spring
查看>>
LDA-math-文本建模
查看>>
0基础学java_枚举
查看>>
11. javacript高级程序设计-DOM扩展
查看>>
go学习笔记-变量作用域
查看>>
如何查找EI 及SCI 索引
查看>>
ODEINT 求解常微分方程(4)
查看>>
仿Google自动提示 SearchSuggess
查看>>
Java算法-符号|
查看>>
【Linux】利用Xvfb关闭chrome的图形化输出
查看>>
web前端常用单词
查看>>
elasticsearch 冷热数据的读写分离
查看>>
NSSet以及NSMutableSet用法
查看>>
[JSOI2008]魔兽地图DotR
查看>>
[forward] Process Heap Viewer
查看>>
AtCoder Grand Contest 016
查看>>
SNS笔记
查看>>
C#基础|值类型和引用类型以及传参问题
查看>>
centos7+hadoop完全分布式集群搭建
查看>>
kubernetes国内镜像拉取
查看>>