Yii example of importing an excel file

Source: Internet
Author: User


Public function Getexcel ($ file ){
$ File = $ _ FILES ['file'] ['tmp _ name'];
Yii: import ("special. extensions. PHPExcel ");
$ PHPExcel = new PHPExcel ();
$ PHPReader = new PHPExcel_Reader_Excel2007 ();
If (! $ PHPReader-> canRead ($ file )){
$ PHPReader = new PHPExcel_Reader_Excel5 ();
If (! $ PHPReader-> canRead ($ file )){
Return false;
           }
        }
$ PHPExcel = $ PHPReader-> load ($ file );
$ CurrentSheet = $ PHPExcel-> getSheet (0); // read the first worksheet
$ AllColumn = $ currentSheet-> getHighestColumn (); // obtain the largest column number.
$ AllRow = $ currentSheet-> getHighestRow (); // obtain the total number of rows.
/** Output from the second row because the first row column name in the excel table */
$ Arr = array ();
For ($ currentRow = 4; $ currentRow <= $ allRow; $ currentRow ++ ){
/** Output from column */
For ($ currentColumn = 'a'; $ currentColumn <= $ allColumn; $ currentColumn ++ ){
$ Val = $ currentSheet-> getCellByColumnAndRow (ord ($ currentColumn)-65, $ currentRow)-> getValue ();/* ord () convert characters into decimal numbers */

/** If garbled characters are output, use the iconv function to convert the Output Content. Convert gb2312 encoding to UTF-8 encoding as follows */
// $ Arr [$ currentRow] [] = iconv ('utf-8', 'gb2312 ', $ val). "\ t ";
$ Arr [$ currentRow] [] = trim ($ val );
            }
        }

// Delete all empty rows
Foreach ($ arr as $ key => $ vals ){
$ Tmp = '';
Foreach ($ vals as $ v ){
$ Tmp. = $ v;
            }
If (! $ Tmp) unset ($ arr [$ key]);
        }
Return $ arr;
}

The sample code is not imported to the database. In fact, it is simple to generate an SQL statement after reading and then execute it to import it to the database. This section will not introduce it.

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.