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,'message'=>'file not found!'); } // 判断文档类型,使用相应的方法,可以解析多种文件,这只是判断两个,其余的自己判断 if($filetype == 'xlsx'){ $filetype = 'Excel2007'; }elseif($filetype == 'xls'){ $filetype = 'Excel5'; } // 引入扩展 Vendor("PHPExcel.PHPExcel.IOFactory"); $objReader = \PHPExcel_IOFactory::createReader($filetype); try{ $PHPReader = $objReader->load($file); }catch(Exception $e){} if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!'); // 获得所有的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)=='='){ return array("error"=>0,'message'=>'can not use the formula!'); exit; } if($cell->getDataType()==\PHPExcel_Cell_DataType::TYPE_NUMERIC){ // $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat(); // $formatcode=$cellstyleformat->getFormatCode(); if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $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('Think');//must, resolve ThinkPHP and PHPExcel conflicts unset($objWorksheet); unset($PHPReader); unset($PHPExcel); unlink($file); return array("error"=>1,"data"=>$array); }
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 '文件不存在'; exit; } // $fileMessage = explode('.',$_FILES[excel][name]); // $filename = $fileMessage[0]; // 获得文件扩展名 $filetype = $fileMessage[1]; //使用函数,获得excel数据 $re = importExecl($file,$filetype); $content = $re['data'][0]['Content']; // P助手函数,自己扩展 P($content);exit; /*逻辑代码*/ } }
and then print it on the page as follows
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('PHPExcel/PHPExcel/Writer/Excel2007.php'); $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('A1', '姓名');//可以指定位置 $phpExcel->getActiveSheet()->setCellValue('B1', '年龄'); $phpExcel->getActiveSheet()->setCellValue('C1', '性别'); $phpExcel->getActiveSheet()->setCellValue('D1', '家庭'); //循环添加数据(根据自己的逻辑) for($i = 2;$i<200;$i++) { $phpExcel->getActiveSheet()->setCellValue('A' . $i, '张鹏飞'.$i); $phpExcel->getActiveSheet()->setCellValue('B' . $i, rand(25,28)); $phpExcel->getActiveSheet()->setCellValue('C' . $i, rand(0,1)); $phpExcel->getActiveSheet()->setCellValue('D' . $i, 'yes'); } $objWriter = new \PHPExcel_Writer_Excel2007($phpExcel); // 文件名 $filename = './a.xlsx'; // 存储文件 $objWriter->save($filename); // 下载文件 // 强制下载函数 代码请转至 http://blog.csdn.net/fei003/article/details/54614097 download('./a.xlsx'); }
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!

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
