ThinkPHP uses PHPExcel to import and export Excel data to a complete instance

Source: Internet
Author: User
This article mainly introduces ThinkPHP's use of PHPExcel to import and export Excel data. It is a very practical function. For more information, see

This article mainly introduces ThinkPHP's use of PHPExcel to import and export Excel data. It is a very practical function. For more information, see

The examples described in this article are used in the Thinkphp development framework. If the same method is used in other frameworks, can many people correctly Import and Export Excel files, the problem is basically caused by errors in the Reference Path of the phpExcel core class. If there is a problem, you must check whether the reference of the path is correct.

The procedure is as follows:

(1) Import Excel

First, upload files on the front-end html page: for example:

Second, process the corresponding PHP File

If (! Empty ($ _ FILES ['file _ stu'] ['name']) {$ tmp_file = $ _ FILES ['file _ stu'] ['tmp _ name']; $ file_types = explode (". ", $ _ FILES ['file _ stu '] ['name']); $ file_type = $ file_types [count ($ file_types)-1];/* It Is Not A. xls file ,, determine if it is an excel file */if (strtolower ($ file_type )! = "Xls") {$ this-> error ('not an Excel file, re-upload');}/* set the upload path */$ savePath = SITE_PATH. '/public/upfile/Excel/';/* Name the uploaded file by time */$ str = date ('ymdhis '); $ file_name = $ str. ". ". $ file_type;/* indicates whether the upload is successful */if (! Copy ($ tmp_file, $ savePath. $ file_name) {$ this-> error ('upload failed');}/** process uploaded Excel data to generate programming data, this function will be noted in the ExcelToArray class in step 3 below: here, the read function in step 3 is called and executed to convert Excel into an array and return it to $ res, then write the database */$ res = Service ('exceltoarray')-> read ($ savePath. $ file_name ); /* important code solves the problem that Thinkphp M and D methods cannot be called. If M and D methods fail in thinkphp, add the following code * // spl_autoload_register (array (' think ', 'autoload');/* write the database to the generated array */foreach ($ r Es as $ k => $ v) {if ($ k! = 0) {$ data ['uid'] = $ v [0]; $ data ['Password'] = sha1 ('123 '); $ data ['email '] = $ v [1]; $ data ['uname'] = $ v [3]; $ data ['center'] = $ v [4]; $ result = M ('user')-> add ($ data); if (! $ Result) {$ this-> error ('database import failed ');}}}}

Third: ExcelToArrary class, used to reference phpExcel and process Excel Data
Note: The ExcelToArrary class is created in addons/services/ExcelToArrary. class. php under the root directory.

Class ExcelToArrary extends Service {public function _ construct () {/* import phpExcel core class Note: If your path is different from mine, you cannot directly copy */include_once ('. /Excel/PHPExcel. php ');}/*** read excel $ filename Path file name $ encode returned data encoding: utf8 by default * do not modify the following basics */public function read ($ filename, $ encode = 'utf-8') {$ objReader = PHPExcel_IOFactory: createReader ('excel5'); $ objReader-> setReadDataOnly (true ); $ objPHPExcel = $ objReader-> load ($ filename); $ objWorksheet = $ objPHPExcel-> getActiveSheet (); $ highestRow = $ objWorksheet-> getHighestRow (); $ highestColumn = $ objWorksheet-> getHighestColumn (); $ highestColumnIndex = PHPExcel_Cell: columnIndexFromString ($ highestColumn); $ excelData = array (); for ($ row = 1; $ row <= $ highestRow; $ row ++) {for ($ col = 0; $ col <$ highestColumnIndex; $ col ++) {$ excelData [$ row] [] = (string) $ objWorksheet-> getCellByColumnAndRow ($ col, $ row)-> getValue () ;}} return $ excelData ;}}

Fourth, the above is all the imported content, and the phpExcel package is appended to the end.

(2) Exporting Excel (easier than importing)

First, find the data in the database that needs to generate Excel, such:

$ Data = M ('user')-> findAll (); // locate the data $ name = 'excelfile '; // The generated Excel file name $ res = service ('exceltoarrary ')-> push ($ data, $ name );

Second, the ExcelToArrary class is used to reference phpExcel and process data.

Class ExcelToArrary extends Service {public function _ construct () {/* import phpExcel core class Note: If your path is different from mine, you cannot directly copy */include_once ('. /Excel/PHPExcel. php ');}/* export excel function */public function push ($ data, $ name = 'excel') {error_reporting (E_ALL ); date_default_timezone_set ('Europe/London '); $ objPHPExcel = new PHPExcel ();/* the following are some settings and author titles */$ objPHPExcel-> getProperties () -> setCreator ("sunshine in turns")-> setLastModifiedBy ("sunshine in turns")-> setTitle ("EXCEL export data")-> setSubject ("EXCEL export data ") -> setDescription ("Backup Data")-> setKeywords ("excel")-> setCategory ("result file");/* The following describes how to process data in Excel, this step is used to retrieve data in a horizontal manner. Do not change the other steps */foreach ($ data as $ k => $ v) {$ num = $ k + 1; $ objPHPExcel-> setActiveSheetIndex (0) // column A of Excel, uid is the key value of the array you found, and so on-> setCellValue ('A '. $ num, $ v ['uid'])-> setCellValue ('B '. $ num, $ v ['email '])-> setCellValue ('C '. $ num, $ v ['Password'])} $ objPHPExcel-> getActiveSheet ()-> setTitle ('user'); $ objPHPExcel-> setActiveSheetIndex (0 ); header ('content-Type: application/vnd. ms-excel '); header ('content-Disposition: attachment; filename = "'.w.name.'.xls"'); header ('cache-Control: max-age = 0 '); $ objWriter = PHPExcel_IOFactory: createWriter ($ objPHPExcel, 'excel5'); $ objWriter-> save ('php: // output'); exit ;}

Third, the above is all exported content, phpExcel site

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.