search
HomeBackend DevelopmentPHP TutorialPHP import Excel file to MySQL database
PHP import Excel file to MySQL databaseMay 31, 2018 am 11:47 AM
excelmysqlphp

This article mainly introduces the example of uploading Excel files to MySQL database using PHP. You can write Excel data into the MySQL database. Interested students can learn about it.

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.

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 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

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 float NOT NULL,
pCount float NOT NULL
);

##2. Generate project

First in ThinkPHP Create a new index.php file in the same directory to generate the project Home.


<?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核心运行文件
?>

3. Upload file form

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


<!DOCTYPE html>
 
<html>
  <head>
    <title>上传文件</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <form id="upload" action="__URL__/upload/" method="post" enctype="multipart/form-data">
      <label for="file">上传文件:</label>
      <input type="file" name="file" id="file"><br />
      <input type="submit" name="submit" value="上传" />
    </form>
  </body>
</html>

4. In /Home/Lib/Action/IndexAction.class Write methods to display the upload form page, upload Excel files, and import Excel files in .php (if there is no expansion package under ThinkPHP/Extend, you need to download it from the ThinkPHP official website, and then unzip the expansion package and put it in)


<?php
 
/**
*
* 导入Excel文件数据到MySQL数据库
*/
class IndexAction extends Action {
 
  /**
   * 显示上传表单html页面
   */
  public function index() {
    $this->display();
  }
 
  /**
   * 上传Excel文件
   */
  public function 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文件
   */
  public function 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 "添加失败!";
    }
  }
 
}
?>

5. Test

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. At the same time, I also hope that everyone will support the PHP Chinese website.

Related recommendations:

phpHow to implement data export

phpSimple winning algorithm example

PHP backtracking algorithm

The above is the detailed content of PHP import Excel file to MySQL database. 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
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

带你把MySQL索引吃透了带你把MySQL索引吃透了Apr 22, 2022 am 11:48 AM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools