search
HomeBackend DevelopmentPHP TutorialThinkphp5+PHPExcel realizes the function of batch uploading table data_php example

This article mainly introduces the batch upload form data function of Thinkphp5+PHPExcel. Friends who need it can refer to the following

1. First, download PHPExcel. Go to the vendor folder, my path is: project/vendor/PHPExcel/, put the downloaded PHPExcel file here

2. Front-end code


<!DOCTYPE html>
<html>
<head>
  <title>批量导入数据</title>
</head>
<body>
<form action="{:url(&#39;/index/index/importExcel&#39;)}" method="post" enctype="multipart/form-data">
  <input type="file" name="myfile"><br/>
  <input type="submit" value="批量的导入">
</form>
</body>
</html>


3.Backend code


/**
  * 导入表格数据
  * 先把文件上传到服务器,然后再读取数据存到数据库
  */
  public function importExcel(){
    header("content-type:text/html;charset=utf-8");
    //上传excel文件
    $file = request()->file(&#39;myfile&#39;);
    //移到/public/uploads/excel/下
    $info = $file->move(ROOT_PATH.&#39;public&#39;.DS.&#39;uploads&#39;.DS.&#39;excel&#39;);
    //上传文件成功
    if ($info) {
      //引入PHPExcel类
      vendor(&#39;PHPExcel.PHPExcel.Reader.Excel5&#39;);
      //获取上传后的文件名
      $fileName = $info->getSaveName();
      //文件路径
      $filePath = &#39;public/uploads/excel/&#39;.$fileName;
      //实例化PHPExcel类
      $PHPReader = new \PHPExcel_Reader_Excel5();
      //读取excel文件
      $objPHPExcel = $PHPReader->load($filePath);
      //读取excel文件中的第一个工作表
      $sheet = $objPHPExcel->getSheet(0);
      $allRow = $sheet->getHighestRow();  //取得总行数
      //$allColumn = $sheet->getHighestColumn();  //取得总列数
      //从第二行开始插入,第一行是列名
      for ($j=2; $j <= $allRow; $j++) {
        $data[&#39;name&#39;] = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
        $data[&#39;tel&#39;] = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
        $data[&#39;addr&#39;] = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();
        $last_id = Db::table(&#39;users&#39;)->insertGetId($data);//保存数据,并返回主键id
        if ($last_id) {
          echo "第".$j."行导入成功,users表第:".$last_id."条!<br/>";
        }else{
          echo "第".$j."行导入失败!<br/>";
        }
      }
    }else{
      echo "上传文件失败!";
    }
  }


Output Result:


Note:

Introduce third-party libraries using vendor(); It is in the form of namespace. The underlying code will automatically replace "." with "/", so when using "/", use "." instead;

The above code can be copied and used directly, but the database related information must be changed to your own !

Summary

The above is the Thinkphp5+PHPExcel implementation introduced by the editor to implement the batch upload form data function. I hope it will be useful to everyone. Help, if you have any questions please ask in our community Q&A.

Related recommendations:

How to import data without refreshing using ThinkPHP, uploadify, upload, PHPExcel

How does phpexcel import excel to process big data code examples

Use PHPExcel to upload data in batches

The above is the detailed content of Thinkphp5+PHPExcel realizes the function of batch uploading table data_php example. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools