Home >Backend Development >PHP Tutorial >Code for phpexcel to import excel into database

Code for phpexcel to import excel into database

WBOY
WBOYOriginal
2016-07-25 08:56:33950browse
This article shares the code for PHP to use phpexcel to import the database. It is a good reference for friends who are interested in studying phpexcel.

phpexcel implements importing content into the database, the code is as follows:

<?php
/**
* phpexcel实例 导入数据库
* by bbs.it-home.org
*/
error_reporting(E_ALL); //开启错误 
set_time_limit(0); //脚本不超时 

date_default_timezone_set('Europe/London'); //设置时间 

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'http://bbs.it-home.org/../Classes/');//设置环境变量 

/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php'; 

//$inputFileType = 'Excel5';    //这个是读 xls的 
    $inputFileType = 'Excel2007';//这个是计xlsx的 
//$inputFileName = './sampleData/example2.xls'; 
$inputFileName = './sampleData/book.xlsx'; 

        echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />'; 
        $objReader = PHPExcel_IOFactory::createReader($inputFileType); 
        $objPHPExcel = $objReader->load($inputFileName); 
        /* 
        $sheet = $objPHPExcel->getSheet(0); 
        $highestRow = $sheet->getHighestRow(); //取得总行数 
        $highestColumn = $sheet->getHighestColumn(); //取得总列 
        */    
        $objWorksheet = $objPHPExcel->getActiveSheet();//取得总行数 
        $highestRow = $objWorksheet->getHighestRow();//取得总列数 

        echo 'highestRow='.$highestRow; 
        echo "<br>"; 
        $highestColumn = $objWorksheet->getHighestColumn(); 
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数 
        echo 'highestColumnIndex='.$highestColumnIndex; 
        echo "<br />"; 
        $headtitle=array(); 
        for ($row = 1;$row <= $highestRow;$row++) 
        { 
            $strs=array(); 
            //注意highestColumnIndex的列数索引从0开始 
            for ($col = 0;$col < $highestColumnIndex;$col++) 
            {  
                $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); 
            }  
              $info = array( 
                      'word1'=>"$strs[0]", 
                    'word2'=>"$strs[1]", 
                    'word3'=>"$strs[2]", 
                    'word4'=>"$strs[3]", 
              ); 
              //引处可放置代码,写入数据库 
              print_r($info); 
              echo '<br />'; 
        } 
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn