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
When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

What is Content Security Policy (CSP) header and why is it important?What is Content Security Policy (CSP) header and why is it important?Apr 09, 2025 am 12:10 AM

CSP is important because it can prevent XSS attacks and limit resource loading, improving website security. 1.CSP is part of HTTP response headers, limiting malicious behavior through strict policies. 2. The basic usage is to only allow loading resources from the same origin. 3. Advanced usage can set more fine-grained strategies, such as allowing specific domain names to load scripts and styles. 4. Use Content-Security-Policy-Report-Only header to debug and optimize CSP policies.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

What is HTTPS and why is it crucial for web applications?What is HTTPS and why is it crucial for web applications?Apr 09, 2025 am 12:08 AM

HTTPS is a protocol that adds a security layer on the basis of HTTP, which mainly protects user privacy and data security through encrypted data. Its working principles include TLS handshake, certificate verification and encrypted communication. When implementing HTTPS, you need to pay attention to certificate management, performance impact and mixed content issues.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use