Use phpExcel to import and export Excel data (detailed analysis in full steps)

Source: Internet
Author: User
This routine is used in the development framework of Thinkphp. if it is used in other frameworks, many people may be able to correctly import and export Excel, the problem is basically caused by an error in the reference path of the phpExcel core class. if there is a problem, you need to work hard. many articles have mentioned how to use phpExcel to import and export Excel data. most of the articles are similar, if it is reproduced, some problems will occur. The following is the usage method summarized by my phpExcel usage routine. Next, I will go directly to the topic.

First of all, I use this routine on the Thinkphp development framework. if I use the same method in other frameworks, can many people correctly import and export Excel files, the problem is basically caused by an error 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.

(1) import Excel

First, upload files on the front-end html page: for example:
The code is as follows:


Second, process the corresponding php file
The code is as follows:
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];

/* Determine whether the file 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;

/* 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 used in the ExcelToArray class in step 3 below.

Note: Here, the read function in step 3 is called and executed to convert Excel into an array and return it to $ res. then, the database is written.

*/
$ 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 ($ res as $ k => $ v)
{
If ($ k! = 0)
{
$ Data ['uid'] = $ v [0];
$ Data ['password'] = sha1 ('000000 ');
$ 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
The code is as follows:
Class ExcelToArrary extends Service {

Public function _ construct (){

/* Import the phpExcel core class. note: If your path is different from mine, you cannot directly copy it */
Include_once ('./Excel/PHPExcel. php ');
}

/**

* Read excel $ filename path file name $ encode the returned data encoding is utf8 by default

* Do not modify the following basic information:

*/

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 = 'Excel file'; // generated Excel file name
$ Res = service ('exceltoarrary ')-> push ($ data, $ name );

Second, the ExcelToArrary class is used to reference phpExcel and process data.
The code is as follows:
Class ExcelToArrary extends Service {

Public function _ construct (){

/* Import the phpExcel core class. note: If your path is different from mine, you cannot directly copy it */
Include_once ('./Excel/PHPExcel. php ');
}

/* Export the 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, such as the author Title */
$ ObjPHPExcel-> getProperties ()-> setCreator ("turning Sunshine ")
-> SetLastModifiedBy ("Sunshine in turns ")
-> SetTitle ("data EXCEL export ")
-> SetSubject ("data EXCEL export ")
-> SetDescription ("backup data ")
-> SetKeywords ("excel ")
-> SetCategory ("result file ");
/* The following figure shows how to process the data in an Excel file and obtain the data horizontally. This step is the main step. 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 the exported content, and the phpExcel package is appended to the end.

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.