Home Backend Development PHP Tutorial Example of how to import data from Excel files to MySQL database

Example of how to import data from Excel files to MySQL database

Mar 09, 2018 pm 02:04 PM
excel mysql data

Recently I am importing data from Excel files into the database. If the website wants to support batch insertion of data, it can create a small program that uploads Excel files and imports the data content into the MySQL database. This article mainly shares with you examples of how to import data from Excel files to MySQL database. I hope it can help you.

Tools to be used:

ThinkPHP: lightweight domestic PHP development framework. It can be downloaded from ThinkPHP official website.

PHPExcel: A PHP class library for Office Excel documents, which is based on Microsoft's OpenXML standard and PHP language. It can be downloaded from the CodePlex official website. ,

1. Design MySQL database product

Create product database

##
CREATE DATABASE product DEFAULTCHARACTER SET utf8 COLLATE utf8_general_ci;
Copy after login

Create pro_info table, table structure


##
CREATE TABLE pro_info(
pId int(4)NOT NULL PRIMARY KEY AUTO_INCREMENT,
pName varchar(20)NOT NULL,
pPrice floatNOT NULL,
pCount floatNOT NULL
);
Copy after login

2. Generate the project

First create a new index.php file in the same directory as ThinkPHP and generate the project Home.

3. Upload file form
##
<?php
  
define(&#39;APP_NAME&#39;,&#39;Home&#39;);  //项目名称
define(&#39;APP_PATH&#39;,&#39;./Home/&#39;); //项目路径
define(&#39;APP_DEBUG&#39;, true);  //开启DEBUG
require &#39;./ThinkPHP/ThinkPHP.php&#39;;  //引入ThinkPHP核心运行文件
?>
Copy after login

Create a new Index folder under the Home/Tpl folder, and create a new index.html file inside it

##
<!DOCTYPE html>
  
<html>
  <head>
    <title>上传文件</title>
    <metacharset="UTF-8">
  </head>
  <body>
    <formid="upload"action="__URL__/upload/"method="post"enctype="multipart/form-data">
      <labelfor="file">上传文件:</label>
      <inputtype="file"name="file"id="file"><br/>
      <inputtype="submit"name="submit"value="上传"/>
    </form>
  </body>
</html>
Copy after login
4. Write methods to display the upload form page, upload Excel files, and import Excel files in /Home/Lib/Action/IndexAction.class.php (if there is no expansion package under ThinkPHP/Extend, you need Download it from the ThinkPHP official website, and then unzip the extension package and put it in)

##
<?php
  
/**
*
* 导入Excel文件数据到MySQL数据库
*/
class IndexAction extends Action {
  
  /**
   * 显示上传表单html页面
   */
  publicfunction index() {
    $this->display();
  }
  
  /**
   * 上传Excel文件
   */
  publicfunction upload() {
    //引入ThinkPHP上传文件类
    import(&#39;ORG.Net.UploadFile&#39;);
    //实例化上传类
    $upload= new UploadFile();
    //设置附件上传文件大小200Kib
    $upload->mixSize = 2000000;
    //设置附件上传类型
    $upload->allowExts =array(&#39;xls&#39;,&#39;xlsx&#39;, &#39;csv&#39;);
    //设置附件上传目录在/Home/temp下
    $upload->savePath =&#39;./Home/temp/&#39;;
    //保持上传文件名不变
    $upload->saveRule =&#39;&#39;;
    //存在同名文件是否是覆盖
    $upload->uploadReplace = true;
    if(!$upload->upload()) { //如果上传失败,提示错误信息
      $this->error($upload->getErrorMsg());
    }else {  //上传成功
      //获取上传文件信息
      $info= $upload->getUploadFileInfo();
      //获取上传保存文件名
      $fileName= $info[0][&#39;savename&#39;];
      //重定向,把$fileName文件名传给importExcel()方法
      $this->redirect(&#39;Index/importExcel&#39;,array(&#39;fileName&#39;=> $fileName), 1,&#39;上传成功!&#39;);
    }
  }
  
  /**
   *
   * 导入Excel文件
   */
  publicfunction importExcel() {
    header("content-type:text/html;charset=utf-8");
    //引入PHPExcel类
    vendor(&#39;PHPExcel&#39;);
    vendor(&#39;PHPExcel.IOFactory&#39;);
    vendor(&#39;PHPExcel.Reader.Excel5&#39;);
  
    //redirect传来的文件名
    $fileName= $_GET[&#39;fileName&#39;];
  
    //文件路径
    $filePath= &#39;./Home/temp/&#39; . $fileName . &#39;.xlsx&#39;;
    //实例化PHPExcel类
    $PHPExcel= new PHPExcel();
    //默认用excel2007读取excel,若格式不对,则用之前的版本进行读取
    $PHPReader= new PHPExcel_Reader_Excel2007();
    if(!$PHPReader->canRead($filePath)) {
      $PHPReader= new PHPExcel_Reader_Excel5();
      if(!$PHPReader->canRead($filePath)) {
        echo&#39;no Excel&#39;;
        return;
      }
    }
  
    //读取Excel文件
    $PHPExcel= $PHPReader->load($filePath);
    //读取excel文件中的第一个工作表
    $sheet= $PHPExcel->getSheet(0);
    //取得最大的列号
    $allColumn= $sheet->getHighestColumn();
    //取得最大的行号
    $allRow= $sheet->getHighestRow();
    //从第二行开始插入,第一行是列名
    for($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
      //获取B列的值
      $name= $PHPExcel->getActiveSheet()->getCell("B". $currentRow)->getValue();
      //获取C列的值
      $price= $PHPExcel->getActiveSheet()->getCell("C". $currentRow)->getValue();
      //获取D列的值
      $count= $PHPExcel->getActiveSheet()->getCell("D". $currentRow)->getValue();
  
      $m= M(&#39;Info&#39;);
      $num= $m->add(array(&#39;pName&#39;=> $name,&#39;pPrice&#39; => $price, &#39;pCount&#39;=> $count));
    }
    if($num > 0) {
      echo"添加成功!";
    }else {
      echo"添加失败!";
    }
  }
  
}
?>
Copy after login

5. Test

Related recommendations:

Share csv import data to mysql instance


A simple way to import data into mysql_MySQL

SqlServer imports data into MySql

The above is the detailed content of Example of how to import data from Excel files to MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

70B model generates 1,000 tokens in seconds, code rewriting surpasses GPT-4o, from the Cursor team, a code artifact invested by OpenAI 70B model generates 1,000 tokens in seconds, code rewriting surpasses GPT-4o, from the Cursor team, a code artifact invested by OpenAI Jun 13, 2024 pm 03:47 PM

70B model, 1000 tokens can be generated in seconds, which translates into nearly 4000 characters! The researchers fine-tuned Llama3 and introduced an acceleration algorithm. Compared with the native version, the speed is 13 times faster! Not only is it fast, its performance on code rewriting tasks even surpasses GPT-4o. This achievement comes from anysphere, the team behind the popular AI programming artifact Cursor, and OpenAI also participated in the investment. You must know that on Groq, a well-known fast inference acceleration framework, the inference speed of 70BLlama3 is only more than 300 tokens per second. With the speed of Cursor, it can be said that it achieves near-instant complete code file editing. Some people call it a good guy, if you put Curs

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

See all articles