PHPExcel (2) import function in the previous section, we have learned the export function of PHPExcel. In this section, we will learn how to use PHPExcel to import data from an Excel file to a database.
PHPExcel usage is the same as described in the previous section: http://blog.csdn.net/liuruiqun/article/details/45667789
1, first download the application, github link: https://github.com/PHPOffice/PHPExcel
2. create the PHPexcel directory under the protected/extensions path and decompress the downloaded PHPExcel file.
3. copy all the extracted content in the classes directory to the protected, extensions, and PHPexcel directories.
4. in the Controller file XXX. Controller. php, first introduce the relevant file
5. Compile the upload method (below is part of the code in the development process)
Public function actionUpload () {spl_autoload_unregister (array ('yibabase', 'autoload'); $ phpExcelPath = Yii: getPathOfAlias ('application. extensions. PHPExcel. PHPExcel '); include ($ phpExcelPath. DIRECTORY_SEPARATOR. 'iofactory. php '); spl_autoload_register (array ('yibase', 'autoload'); // if (isset ($ _ POST ['submit']) {$ file_temp = CUploadedFile: getInstanceByName ('Files'); $ file1 = $ file_temp-> getName (); $ file = iconv ("UTF-8", "gb2312 ", $ file1); // Chinese garbled characters $ file_dir = YiiBase: getPathOfAlias ('webroot '). '/assets/upload/subject /'. $ file; $ file_temp-> saveAs ($ file_dir, true); $ objReader = PHPExcel_IOFactory: createReader ('excel5 '); // use excel2007 for 2007 format $ objPHPExcel = $ objReader-> load ($ file_dir); $ sheet = $ objPHPExcel-> getSheet (0 ); $ total_line = $ sheet-> getHighestRow (); // get the total number of rows // $ total_column = $ sheet-> getHighestColumn (); // obtain the total number of columns for ($ row = 2; $ row <= $ total_line; $ row ++) {$ a = $ objPHPExcel-> getActiveSheet () -> getCell ("". $ row)-> getValue (); // obtain the value (ID) of column A $ B = $ objPHPExcel-> getActiveSheet ()-> getCell ("B ". $ row)-> getValue (); // obtain the value (ID) of column B $ model = new Subject; $ model-> name = $; $ model-> credit = $ B; $ model-> save () ;}$ this-> redirect (array ('admin '));} $ this-> render ('upload ');}
Code implementation:
Upload the Excel file to the/assets/upload/subject/directory, and import the values of column A and column B in the Excel file to the name and credit in the data table Subject respectively.