search
HomeBackend DevelopmentPHP TutorialExcelFileParser processes excel to obtain data and can be imported into the database in batches_PHP tutorial

ExcelFileParser处理excel获得数据 可作批量导入到数据库

提交表单





Excel数据获取演示




   

     
Excel数据获取演示

     

       

           
           
       

     

   



提交处理
[php]
/**
* CopyRight (c) 2009,
* All rights reserved.
* File name:
* Abstract:
*
* @author Monday ixqbar@hotmail.com
* @version
*/

class IndexAction extends Action
{
    /**
* Constructor
*/
    public function __construct()
    {
        parent::__construct();
    }
    /**
* Default index page
*/
    public function index()
    {
        $this->display();
    }
    /**
* Submit processing
*/
    public function parse()
    {
       /**
* $_FILES Array Description
File name
*                                                                                                                                                                                                                               "] = & Gt; Error (0 Success 1 File is too large than upload_max_filesize2 files are too large than max_file3 upload incomplete 4 without upload files)
*[" size "] = & gt; file size (unit: kb)
* }
* }
*/
        $return=array(0,'');
        /**
* Determine whether to submit
* is_uploaded_file (file name) is used to determine whether the specified file is uploaded using the POST method to prevent illegal submission. It is usually used together with move_upload_file to save the uploaded file to the specified path
*/
        if(!isset($_FILES) || !is_uploaded_file($_FILES['excel']['tmp_name']))
        {
            $return=array(1,'提交不合法');
        }
        //处理
        if(0 == $return[0])
        {
            import('@.Util.ExcelParser');
            $excel=new ExcelParser($_FILES['excel']['tmp_name']);
            $return=$excel->main();
        }
        //输出处理
        print_r($return);
    }
}
?>
[/php]

处理类
[php]
/**
* CopyRight (c) 2009,
* All rights reserved.
* File name: excel data acquisition
* Abstract:
*
* @author Monday ixqbar@hotmail .com
* @version 0.1
*/
class ExcelParser
{
    private $_data=array(0,'');
    private $_excel_handle;
    private $_excel=array();
    /**
* Constructor
* @param $filename Temporary file name of uploaded file
*/
    public function __construct($filename)
    {
        /**
* Introduce excelparser class
* Common method is
* requires path.'excelparser.php';
* Import is ThinkPHP’s own import class method
*/
        import('@.Util.PHPExcelParser.excelparser','','.php');
        $this->_excel_handle=new ExcelFileParser();
        //错误获取
        $this->checkErrors($filename);
    }
    /**
* Error checking
*/
    private function checkErrors($filename)
    {
        /**
*Method 1
*/
        $error_code=$this->_excel_handle->ParseFromFile($filename);
        /**
         * 方法二
         * $file_handle = fopen($this->_filename,'rb');
         * $content = fread($file_handle,filesize($this->_filename));
         * fclose($file_handle);
         * $error_code = $this->_excel->ParseFromString($content);
         * unset($content,$file_handle);
        */
        switch($error_code)
        {
            case 0:
                //无错误不处理
                break;
            case 1:
                $this->_data=array(1,'文件读取错误(Linux注意读写权限)');
                break;
            case 2:
                $this->_data=array(1,'文件太小');
                break;
            case 3:
                $this->_data=array(1,'读取Excel表头失败');
                break;
            case 4:
                $this->_data=array(1,'文件读取错误');
                break;
            case 5:
                $this->_data=array(1,'文件可能为空');
                break;
            case 6:
                $this->_data=array(1,'文件不完整');
                break;
            case 7:
                $this->_data=array(1,'读取数据错误');
                break;
            case 8:
                $this->_data=array(1,'版本错误');
                break;
        }
        unset($error_code);
    }
    /**
* Excel information acquisition
*/
    private function getExcelInfo()
    {
        if(1==$this->_data[0])return;
        /**
* Get the number of sheets
* Get the rows and columns corresponding to the sheet units
 */
        $this->_excel['sheet_number']=count($this->_excel_handle->worksheet['name']);
        for($i=0;$i_excel['sheet_number'];$i++)
        {
            /**
          * Rows in columns                                                   */
            $row=$this->_excel_handle->worksheet['data'][$i]['max_row'];
            $col=$this->_excel_handle->worksheet['data'][$i]['max_col'];
            $this->_excel['row_number'][$i]=($row==NULL)?0:++$row;
            $this->_excel['col_number'][$i]=($col==NULL)?0:++$col;
            unset($row,$col);
        }
    }
    /**
* Chinese processing function
* @return
*/
    private function uc2html($str)
    {
        $ret = '';
        for( $i=0; $i        {
            $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
            $ret .= ''.$charcode.';';
        }
        return mb_convert_encoding($ret,'UTF-8','HTML-ENTITIES');
    }
    /**
* Excel data acquisition
*/
    private function getExcelData()
    {
        if(1==$this->_data[0])return;

        //修改标记
        $this->_data[0]=1;
        //获取数据
        for($i=0;$i_excel['sheet_number'];$i++)
        {
            /**
                                                                                 */
            for($j=0;$j_excel['row_number'][$i];$j++)
            {
                /**
                              */
                for($k=0;$k_excel['col_number'][$i];$k++)
                {
                    /**
                 * array(4) {
                                                           => Font
* ["data"] => Data
                                                                    */
                    $data=$this->_excel_handle->worksheet['data'][$i]['cell'][$j][$k];
                    switch($data['type'])
                    {
                        case 0:
                            //字符类型
                            if($this->_excel_handle->sst['unicode'][$data['data']])
                            {
                                //中文处理
                                $data['data'] = $this->uc2html($this->_excel_handle->sst['data'][$data['data']]);
                            }
                            else
                            {
$data['data'] = $this->_excel_handle->sst['data'][$data['data']];
                                                                     case 1:
                                                                                                                                                Case 2:
🎜> case 3:
Date
                                                                                                                                               $this->_data[1][$i][$j][$k]=$data['data'];
                                                                                                                                               🎜> public function main()
{
//Get Excel information
                                                                                                                                  getExcelInfo();                              > }
}

?>





http://www.bkjia.com/PHPjc/444996.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/444996.html

TechArticle

ExcelFileParser processes excel to obtain data, which can be imported into the database in batches to submit the form! DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml...





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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools