• PHP 导出csv


    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' . " ";

    $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']) . " ";
    }

    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;
    }

  • 相关阅读:
    sscanf 与 ssprintf 用法 (转载--https://www.cnblogs.com/Anker/p/3351168.html)
    PYTHON网络爬虫与信息提取[信息的组织与提取](单元五)
    PYTHON网络爬虫与信息提取[BeautifulSoup](单元四)
    PYTHON网络爬虫与信息提取[网络爬虫协议](单元二)
    Python网络爬虫与信息提取[request库的应用](单元一)
    scikit-learn实现ebay数据分析 的随笔
    machine leanring 笔记 vectorization
    machine learning 笔记 normal equation
    machine leanring 笔记 octave命令笔记
    UVa 1354 天平难题 Mobile Computing
  • 原文地址:https://www.cnblogs.com/floraCnblogs/p/php-import-or-export.html
Copyright © 2020-2023  润新知