How does ThinkPHP import Excel files based on PHPExcel?

Source: Internet
Author: User
This article mainly introduces ThinkPHP's method of importing Excel files based on PHPExcel. it gives a detailed description of the uploading, reading, and writing of Excel files to the database, it is of practical value in the process of project development. if you need it, you can refer to the example in this article to describe how ThinkPHP Imports Excel files based on PHPExcel. Share it with you for your reference. The specific method is as follows:

The main knowledge point is to use PHPExcel to import Excel data. after these days of testing, you can still use xls or xlsx to obtain Excel data.
: Http://phpexcel.codeplex.com/

Development ideas:

1. Upload the Excel file to the server first.

2. obtain the Excel file content on the server

3. write data to the database

1. Upload an Excel file, Using the built-in Upload method "\ Think \ Upload ();" in PHP, you can easily implement it. For this reason, I sorted out the simplest way to use this method.

The code is as follows:

/**
* TODO file Upload method
* @ Param $ fileid form file name value
* @ Param $ dir upload to the $ dir folder in the uploads Directory
* @ Param int $ maxsize maximum upload limit. the default value is 1024000 bytes.
* @ Param array $ exts: the default object type that can be uploaded is array ('GIF', 'jpg ', 'jpeg', 'bmp ', and 'PNG ')
* @ Return array returns array, failure status = 0 success status = 1, filepath = newspost/2014-9-9/a.jpg
*/
Function uploadfile ($ fileid, $ dir, $ maxsize = 5242880, $ exts = array ('GIF', 'jpg ', 'jpeg', 'bmp ', 'PNG '), $ maxwidth = 430 ){
$ Upload = new \ Think \ Upload (); // instantiate the upload class
$ Upload-> maxSize = $ maxsize; // sets the attachment upload size, in bytes (the image size is 1 MB.
$ Upload-> exts = $ exts; // you can specify the attachment upload type.
$ Upload-> rootPath = './uploads/'; // you can specify the root directory for uploading attachments.
$ Upload-> savePath = $ dir. '/'; // sets the attachment upload (sub) directory.
// Upload a file
$ Info = $ upload-> upload ();

If (! $ Info) {// upload error message
Return array (status => 0, msg => $ upload-> getError ());
} Else {// Upload successful
Return array (status => 1, msg => 'upload succeeded ', filepath => $ info [$ fileid] ['savepath']. $ info [$ fileid] ['savename']);
}
}

The index file is uploaded to the ThinkPHP Portal by default. in the uploads folder where php is located, this method returns a data. status = 1 is successful. We also recommend that you write the function module or encapsulate it, the entire system should have an agreement at the beginning of the architecture. if necessary, the return value should be in the form of an array, and the return value will be returned successfully.

The code is as follows:

Return array (status => 1, data =>..., info => .....)


Can be returned if the failure occurs.

The code is as follows:

Array (status-> 0, info => 'can indicate the cause of the error ',....)


In this way, the unified method is conducive to standardized development. when you look at the code during team collaboration, you can improve efficiency and reduce the running of thinking. to put it far away, the upload method is called as follows:

The code is as follows:

// Excel file
If (! Empty ($ _ FILES ['XLS '] ['name']) {
$ Upload = uploadfile ('XLS ', 'tempxls', 5242880, array ('XLS ', 'xlsx '));
If ($ upload ['status']) {
$ Path = $ upload ['filepath'];
} Else {
$ This-> error ($ upload ['MSG ']);
}
}

2. obtain Excel data

1. first introduce the PHPExcel class library

The code is as follows:

Require_once 'Module/PHPExcel/Classes/PHPExcel/IOFactory. php ';

2. obtain 0th Excel tables (Sheet1)

The code is as follows:

// Obtain an excel file
$ ObjPHPExcel = \ PHPExcel_IOFactory: load ("uploads/$ path ");
$ ObjPHPExcel-> setActiveSheetIndex (0 );
$ Sheet0 = $ objPHPExcel-> getSheet (0 );

3. get the number of rows and read the data $ data array

The code is as follows:

$ RowCount = $ sheet0-> getHighestRow (); // Number of excel rows
$ Data = array ();
For ($ I = 2; $ I <= $ rowCount; $ I ++ ){
$ Item ['name'] = $ this-> getExcelValue ($ sheet0, 'A'. $ I );
$ Item ['sex'] = $ this-> getExcelValue ($ sheet0, 'B'. $ I );
$ Item ['Contact '] = $ this-> getExcelValue ($ sheet0, 'C'. $ I );
$ Item ['remark'] = $ this-> getExcelValue ($ sheet0, 'd'. $ I );
$ Item ['addtime'] = $ this-> getExcelValue ($ sheet0, 'E'. $ I );

$ Data [] = $ item;
}

3. save it to the database

The code is as follows:

$ Success = 0;
$ Error = 0;
$ Sum = count ($ data );
Foreach ($ data as $ k => $ v ){
If (M ('temp _ area3 ')-> data ($ v)-> add ()){
$ Success ++;
} Else {
$ Error ++;
}
}

Echo "total {$ sum} records, successful {$ success} records, failed {$ error} records. ";

This is a success! I hope this article will help you with ThinkPHP framework programming.

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.