Home Backend Development PHP Tutorial Introduction to the use process of PHPExcel

Introduction to the use process of PHPExcel

Jul 02, 2017 am 09:48 AM
phpexcel thinkphp3.2

I am using the thinkphp framework

I encountered a scenario where the deliveryman needed to send notification text messages to users one by one after delivering the goods. The efficiency was too low, so I thought of template text messages,

When it comes to efficiency issues, I designed it like this. He imported Excel, I parsed it through phpExcel, matched the name, phone number, order number, order type

and then sent a notification text message to the user. ,Send different order query addresses and notification information according to the order type

---------------------------------- -------------------------------------------------- -------------------------------------------------- -------

This article mainly records my process of using PHPExcel

This article is not Yuanchuang, it was compiled after reading many posts by great masters, and even copied. Code, but I did not record the specific original text, so I will not post it bit by bit.

This article is only for my own recording and study purposes

-------- -------------------------------------------------- -------------------------------------------------- ----------------------------

1: Download PHPExcel

can be downloaded from the official website, I Also uploaded the document http://download.csdn.net/detail/fei003/9851672

2 Put PHPExcel into the project

Put the decompressed file of PHPExcel into Thinkphp/Library /Vendor

3. Encapsulate the operation method into a function (or class library) to facilitate your own use

excel.PHP function

<?php
/**
 * Created by PhpStorm.
 * User: 飞
 * Date: 2017/6/13
 * Time: 10:20
 * 导入excel文件,对表格进行解析
 */
function importExecl($file,$filetype){
    if(!file_exists($file)){
        return array("error"=>0,&#39;message&#39;=>&#39;file not found!&#39;);
    }
    // 判断文档类型,使用相应的方法,可以解析多种文件,这只是判断两个,其余的自己判断
    if($filetype == &#39;xlsx&#39;){
        $filetype = &#39;Excel2007&#39;;
    }elseif($filetype == &#39;xls&#39;){
        $filetype = &#39;Excel5&#39;;
    }
    // 引入扩展
    Vendor("PHPExcel.PHPExcel.IOFactory");
    $objReader = \PHPExcel_IOFactory::createReader($filetype);

    try{
        $PHPReader = $objReader->load($file);
    }catch(Exception $e){}
    if(!isset($PHPReader)) return array("error"=>0,&#39;message&#39;=>&#39;read error!&#39;);
    // 获得所有的sheets表格
    $allWorksheets = $PHPReader->getAllSheets();
    $i = 0;
    //对sheet表格遍历分析
    foreach($allWorksheets as $objWorksheet){
        // 获得sheet表格的标题
        $sheetname=$objWorksheet->getTitle();
        // 获得总行数
        $allRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        // 获得总列数
        $allColumn = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $array[$i]["Title"] = $sheetname;
        $array[$i]["Cols"] = $allColumn;
        $array[$i]["Rows"] = $allRow;
        $arr = array();
        // 对合并的单元格进行分析
        $isMergeCell = array();
        foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells
            foreach (\PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
                $isMergeCell[$cellReference] = true;
            }
        }
        for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){
            $row = array();
            for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){;
                $cell =$objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
                $afCol = \PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);
                $bfCol = \PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);
                $col = \PHPExcel_Cell::stringFromColumnIndex($currentColumn);
                $address = $col.$currentRow;
                $value = $objWorksheet->getCell($address)->getValue();
                if(substr($value,0,1)==&#39;=&#39;){
                    return array("error"=>0,&#39;message&#39;=>&#39;can not use the formula!&#39;);
                    exit;
                }
                if($cell->getDataType()==\PHPExcel_Cell_DataType::TYPE_NUMERIC){
                    // $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();
                    // $formatcode=$cellstyleformat->getFormatCode();
                    if (preg_match(&#39;/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i&#39;, $formatcode)) {
                        $value=gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($value));
                    }else{
                        $value=\PHPExcel_Style_NumberFormat::toFormattedString($value,$formatcode);
                    }
                }
                if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){
                    $temp = $value;
                }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){
                    $value=$arr[$currentRow-1][$currentColumn];
                }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){
                    $value=$temp;
                }
                $row[$currentColumn] = $value;
            }
            $arr[$currentRow] = $row;
        }
        $array[$i]["Content"] = $arr;
        $i++;
    }
    // spl_autoload_register(&#39;Think&#39;);//must, resolve ThinkPHP and PHPExcel conflicts
    unset($objWorksheet);
    unset($PHPReader);
    unset($PHPExcel);
    unlink($file);
    return array("error"=>1,"data"=>$array);
}
Copy after login


Note: When instantiating, add \


# to the namespace. It’s easy to use, as follows Use the code

<?php
namespace PhpExcel\Controller;
use Think\Controller;

/**
 * Created by PhpStorm.
 * User: 飞
 * Date: 2017/6/7
 * Time: 11:26
 */
class IndexController extends Controller
{
    public function index()
    {
        $this->display();
    }

    public function importExcel()
    {
        // 表单提交文件过来
        // 获得文件路径
        $file = $_FILES[excel][tmp_name];
        if(!file_exists($file)){
            echo &#39;文件不存在&#39;;
            exit;
        }
        //
        $fileMessage = explode(&#39;.&#39;,$_FILES[excel][name]);
        // $filename = $fileMessage[0];
        // 获得文件扩展名
        $filetype = $fileMessage[1];
        //使用函数,获得excel数据
        $re = importExecl($file,$filetype);
        $content = $re[&#39;data&#39;][0][&#39;Content&#39;];
        // P助手函数,自己扩展
        P($content);exit; /*逻辑代码*/
    }
}
Copy after login

and then print it on the page as follows

Introduction to the use process of PHPExcel

From the page, the data analysis is very good

Of course, take After getting the data, you can do whatever you want. . . hey-hey

------------------------------------------- -------------------------------------------------- ------

Another scenario is to generate your own data into an excel table

The code is as follows

public function outPortExcel()
{
    // 引入文件
    Vendor("PHPExcel.PHPExcel");
    vendor(&#39;PHPExcel/PHPExcel/Writer/Excel2007.php&#39;);
    $phpExcel = new \PHPExcel();
    $phpExcel->getProperties()->setTitle("Office 2007 XLSX Test Document title");
    $phpExcel->getProperties()->setSubject("Office 2007 XLSX Test Document subject");
    //单独添加数据
    $phpExcel->setActiveSheetIndex(0);
    $phpExcel->getActiveSheet()->setCellValue(&#39;A1&#39;, &#39;姓名&#39;);//可以指定位置
    $phpExcel->getActiveSheet()->setCellValue(&#39;B1&#39;, &#39;年龄&#39;);
    $phpExcel->getActiveSheet()->setCellValue(&#39;C1&#39;, &#39;性别&#39;);
    $phpExcel->getActiveSheet()->setCellValue(&#39;D1&#39;, &#39;家庭&#39;);
    //循环添加数据(根据自己的逻辑)
    for($i = 2;$i<200;$i++) {
        $phpExcel->getActiveSheet()->setCellValue(&#39;A&#39; . $i, &#39;张鹏飞&#39;.$i);
        $phpExcel->getActiveSheet()->setCellValue(&#39;B&#39; . $i, rand(25,28));
        $phpExcel->getActiveSheet()->setCellValue(&#39;C&#39; . $i, rand(0,1));
        $phpExcel->getActiveSheet()->setCellValue(&#39;D&#39; . $i, &#39;yes&#39;);
    }
    $objWriter = new \PHPExcel_Writer_Excel2007($phpExcel);
    // 文件名
    $filename = &#39;./a.xlsx&#39;;
    // 存储文件
    $objWriter->save($filename);

    // 下载文件
    // 强制下载函数 代码请转至 http://blog.csdn.net/fei003/article/details/54614097
    download(&#39;./a.xlsx&#39;);
}
Copy after login

ok, this is the process of using PHPExcel

The above is the detailed content of Introduction to the use process of PHPExcel. 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

Video Face Swap

Video Face Swap

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

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)

Complete Guide: How to process Excel files using php extension PHPExcel Complete Guide: How to process Excel files using php extension PHPExcel Jul 28, 2023 pm 10:01 PM

Complete Guide: How to Process Excel Files Using PHP Extension PHPExcel Introduction: Excel files are often used as a common format for data storage and exchange when processing large amounts of data and statistical analysis. Using the PHP extension PHPExcel, we can easily read, write and modify Excel files to effectively process Excel data. This article will introduce how to use the PHP extension PHPExcel to process Excel files and provide code examples. 1. Install PHPExc

PHP development: Use PHPExcel to process Excel files PHP development: Use PHPExcel to process Excel files Jun 15, 2023 pm 03:45 PM

With the advent of the digital age, data has become the most important part of our daily lives and work, and Excel files have become one of the important tools for data processing. I believe that many PHP developers will often encounter the use of Excel files for data processing and operations at work. This article will introduce you to the methods and precautions for using the PHPExcel library to process Excel files. What is PHPExcel? PHPExcel is a PHP class

How to use phpexcel to convert Excel files to CSV files and open them How to use phpexcel to convert Excel files to CSV files and open them Mar 27, 2023 pm 04:16 PM

​PHPEXCEL is an excellent PHP class library for reading and writing Excel files. It provides a very sufficient API that allows us to use PHP to read and write Excel files. Sometimes, we need to convert Excel files into CSV files for use on some occasions. So, this article mainly describes how to use the PHPEXCEL class library to convert Excel files into CSV files and open them.

Why phpexcel has become the focus of PHP developers Why phpexcel has become the focus of PHP developers Mar 27, 2023 pm 06:15 PM

PHPExcel is an open source PHP library for processing Microsoft Excel files. It can read, create, modify and save Excel files. It is a powerful and highly customizable tool that can be used to handle tasks such as data analysis, report generation, data import and export, etc. In this article, we will introduce why PHPExcel has become the focus of PHP developers.

How to use PHPExcel to process Excel files? How to use PHPExcel to process Excel files? Jun 01, 2023 pm 02:01 PM

PHPExcel is an open source PHP library for processing Microsoft Excel (.xls and .xlsx) files. It can read, write and operate Excel files, and provides a wealth of functions and methods. Using the PHPExcel library in PHP projects, you can quickly and easily process Excel files and implement functions such as data import, export and data processing. This article will introduce how to use PHPExcel to process Excel files. 1. To install PHPExcel, use

How to hide module name in thinkphp3.2 How to hide module name in thinkphp3.2 Dec 09, 2022 am 10:11 AM

How to hide the module name in thinkphp3.2: 1. Create a ".htaccess" file in the root directory; 2. Add "RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d"; 3. Add "config.php" under the corresponding module "Set the access module in ".

Create Excel files using PHP and PHPExcel Create Excel files using PHP and PHPExcel May 11, 2023 am 08:40 AM

In today's era of rapid information transfer, data processing and storage have become increasingly important. The use of Excel tables is the first choice for many people because Excel tables can integrate various data and can be easily analyzed and processed. In order to complete the creation of Excel tables more efficiently, we can use two powerful tools, PHP and PHPExcel. In this article, we will introduce how to create Excel files using PHP and PHPExcel. 1. Install PHPExcel first

PHP development tips: How to use PHPExcel and PHPExcel_IOFactory to operate MySQL database PHP development tips: How to use PHPExcel and PHPExcel_IOFactory to operate MySQL database Jul 02, 2023 pm 02:28 PM

PHP development tips: How to use PHPExcel and PHPExcel_IOFactory to operate MySQL database Overview: In web development, processing Excel files is a common and important task. PHPExcel is a powerful and easy-to-use PHP library that can help us read and write Excel files. This article will introduce how to use PHPExcel and PHPExcel_IOFactory libraries to operate MySQL database. step 1

See all articles