无法导入xls / xlsx文件

时间:2017-11-01 06:46:16

标签: php excel import

我正在使用PHP将excel文件导入MySQL。以下代码适用于csv文件,但不适用于xls / xlsx文件格式。

<html>
  <head>
    <meta charset="utf-8">
    <title>Import Excel to MySQL using PHP </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>
  <body style="padding-top:50px;">

<div class="container"><!-- container class is used to centered  the body of the browser with some decent width-->
    <div class="row"><!-- row class is used for grid system in Bootstrap-->
        <div class="col-md-4 col-md-offset-4"><!--col-md-4 is used to create the no of colums in the grid also use for medimum and large devices-->
            <div class="login-panel panel panel-success">
                <div class="panel-heading">
                    <h3 class="panel-title">Import here</h3>
                </div>
                <div class="panel-body">

                    <form method="post" action="import.php" enctype="multipart/form-data">
                        <fieldset>
                            <div class="form-group">
                              <input type="file" name="file"/>
                            </div>
                        <input class="btn btn-success" type="submit" name="submit_file" value="Submit"/>
                        </fieldset>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Import.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
/*
Developer: Ehtesham Mehmood
Site:      PHPCodify.com
Script:    Import Excel to MySQL using PHP and Bootstrap
File:      import.php
*/

// Including database connections
require_once 'db_con.php';

if(isset($_POST["submit_file"]))
{
 $file = $_FILES["file"]["tmp_name"];

 $file_open = fopen($file,"r");
 while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
 {
  $employee_name = $csv[0];
  $employee_designation = $csv[1];
  $employee_salary = $csv[2];

  $stmt = $DBcon->prepare("INSERT INTO employee(employee_name,employee_designation,employee_salary) VALUES(:employee_name,:employee_designation,:employee_salary)");

  $stmt->bindparam(':employee_name', $employee_name);
  $stmt->bindparam(':employee_designation', $employee_designation);
  $stmt->bindparam(':employee_salary', $employee_salary);
  $stmt->execute();
 }
}

echo "Imported Successfully";
?>

2 个答案:

答案 0 :(得分:0)

PHP中 xls 文件的不同示例。这里我附上代码示例。

解析行:

$xlsx = new SimpleXLSX('File_For_Import.xlsx');
        list($num_cols, $num_rows) = $xlsx->dimension();
        $f = 0;
        foreach ($xlsx->rows() as $r) {
            // Ignore the inital name row of excel file
            if ($f == 0) {
                $f++;
                continue;
            }
            //sample column-names for your understanding.  
            for ($i = 0; $i < $num_cols; $i++) {
                if ($i == 0) 
                    $data['employee_name'] = $r[$i];
                else if($i == 1) 
                     $data['employee_designation'] = $r[$i];  
                else if ($i == 2)
                     $data['employee_salary'] = $r[$i];    
             //write code according to your DB.   
            }
            $data['class_id'] = $this->input->post('class_id');
            $this->db->insert('student', $data);
            //print_r($data);
        }

答案 1 :(得分:0)

这是因为Excel文件xls或xlsx不是CSV文件。

有3种不同的文件格式需要3种不同的方法。 您需要找到PHP的Excel库,例如EasyXLS

<?php
        if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['filename'] ) ){

            $filename=filter_input( INPUT_POST, 'filename', FILTER_SANITIZE_STRING );

            if( $filename && realpath( $filename ) ){
                ob_clean();

                $hndl=fopen( $filename, 'r' );
                $html=array();

                $html[]="<table id='toggle-vis'>";
                while ( ( $line = fgetcsv( $hndl ) ) !== false ){
                    $html[]="<tr>";
                    foreach( $line as $cell )$html[]="<td>$cell</td>";
                    $html[]="</tr>";
                }
                $html[]="</table>";

                fclose( $hndl );

                header( 'Content-Type: text/html' );
                exit( implode( PHP_EOL, $html ) );
            }
        }
?>
<!doctype html>
<html>
    <head>
        <title>csv manipulations</title>
        <script>
            /*
                basic ajax function
            */
            function ajax(m,u,p,c,o){
                /*
                    Method,Url,Params,Callback,Options
                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push( n+'='+p[ n ] );

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }

            /*
                event handler assigned to each `a` within the list ( li.active > a )
            */
            function getcsvdata(e){
                try{
                    e.preventDefault();

                    var method='post';
                    var url=location.href;
                    var params={
                        filename:e.target.innerHTML
                    };
                    var callback=csvcallback;
                    var options={};

                    ajax.call( this, method, url, params, callback, options );

                }catch( err ){
                    console.warn( err );
                }
            }

            /*
                ajax callback to process the response from the php script at the top
            */
            function csvcallback( data ){
                try{

                    var table=document.getElementById('toggle-vis');
                    if( table ){
                        var parent=table.parentNode;
                        parent.removeChild( table );

                        parent.insertAdjacentHTML('beforeend',data);
                    }
                }catch( err ){
                    console.warn( err );
                }
            }


            /*
                Bind event handlers to each `a` in list 
            */
            document.addEventListener('DOMContentLoaded',function(){
                var col=Array.prototype.slice.call( document.querySelectorAll('li.active > a') );
                col.forEach(function(e){
                    e.addEventListener('click',getcsvdata,false);
                });
            }, false );
        </script>
    </head>
    <body>
        <h1>CSV Files</h1>
        <ul id='list'>
        <?php

            /* edit to suit */
            $dir='c:/temp2/csvfiles';


            $col=glob( $dir . '/*.csv' );
            if( !empty( $col ) ){
                foreach( $col as $file ){
                    echo "<li class='active'><a href='#'>$file</a></li>";
                }
            }
        ?>
        </ul>
        <table id='toggle-vis'>
            <tr>
                <td>csv data to appear here when links clicked</td>
            </tr>
        </table>
    </body>
</html>

有关importing Excel file into MySQL using PHP的更多信息。