Thinkphp _php instances of methods for importing Excel files based on Phpexcel

Source: Internet
Author: User
Tags rowcount

The example in this article describes how thinkphp imports Excel files based on Phpexcel. Share to everyone for your reference. The specific methods are as follows:

Main knowledge point, import Excel data with Phpexcel after a few days of testing or can, XLS,XLSX can get Excel data.
Download Address: http://phpexcel.codeplex.com/

Development ideas:

1. Upload the Excel file to the server first

2. Get Server Excel file contents

3. Write to Database

First, upload Excel file , using PHP with the Upload Method "\think\upload ();", can be easily realized. So I've sorted out the easiest way to use this method

Copy Code code as follows:
/**
* TODO Upload File method
* @param $fileid form the name value of form file
* @param $dir uploaded to the $dir folder in the uploads directory.
* @param int $maxsize maximum upload limit, default 1024000 byte
* @param array $exts allow uploading file type default array (' GIF ', ' jpg ', ' jpeg ', ' BMP ', ' PNG ')
* @return Array returned array, failed status=0 successful 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 ()///materialized upload class
$upload->maxsize = $maxsize//Set attachment upload size, Unit bytes (micro-letter image Limit 1M
$upload->exts = $exts;//Set attachment upload type
$upload->rootpath = './uploads/'; Set attachment upload root directory
$upload->savepath = $dir. '/'; Set attachment upload (sub) directory
Uploading files
$info = $upload->upload ();

if (! $info) {//Upload error message
Return Array (status=>0,msg=> $upload->geterror ());
}else{//Upload Successful
Return Array (status=>1,msg=> ' upload success ',filepath=> $info [$fileid] [' Savepath ']. $info [$fileid] [' savename ']);
}
}

Here the default upload to the thinkphp entry file index.php folder uploads, this method returns a data, state Status=1 when the success, but also recommended that when you write functional modules or encapsulation, the entire system in the early stages of the architecture should have agreed, Returns a value in the form of an array if necessary, successfully returning

Copy Code code as follows:
Return Array (Status=>1,data=>....,info=> ...)

Can return when failed

Copy Code code as follows:
Array (status->0,info=> ' can explain the cause of the error ',....)

Such a unified way to facilitate the development of norms, team cooperation when looking at the code can improve efficiency, reduce the thinking of the operation, said far, the method of uploading the way to call the following:

Copy Code code 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 ']);
}
}

Second, get Excel data

1. First of all, we need to introduce Phpexcel class library

Copy Code code as follows:
Require_once ' module/phpexcel/classes/phpexcel/iofactory.php ';

2. Get Excel No. 0 sheet (SHEET1)

Copy Code code as follows:
Get Excel Files
$objPHPExcel = \phpexcel_iofactory::load ("uploads/$path");
$objPHPExcel->setactivesheetindex (0);
$sheet 0= $objPHPExcel->getsheet (0);

3. Get the number of rows and read the data out $data array

Copy Code code as follows:
$rowCount = $sheet 0->gethighestrow ();//excel number of rows
$data =array ();
for ($i = 2; $i <= $rowCount; $i + +) {
$item [' name ']= $this->getexcelvalue ($sheet 0, ' A '. $i);
$item [' Sex ']= $this->getexcelvalue ($sheet 0, ' B '. $i);
$item [' Contact ']= $this->getexcelvalue ($sheet 0, ' C '. $i);
$item [' Remark ']= $this->getexcelvalue ($sheet 0, ' D '. $i);
$item [' Addtime ']= $this->getexcelvalue ($sheet 0, ' E '. $i);

$data []= $item;
}

Third, last saved to the database

Copy Code code 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} bar, succeeded {$success}, failed {$error}. ";

It's done! I hope this article will be helpful to everyone's thinkphp framework program design.

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.