PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label html-input. Show all posts
Showing posts with label html-input. Show all posts

Saturday, October 15, 2022

[FIXED] How do I get the value of text input field using JavaScript?

 October 15, 2022     dom, html-input, javascript     No comments   

Issue

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

And this is my JavaScript code:

<script type="text/javascript">
  function searchURL(){
    window.location = "http://www.myurl.com/search/" + (input text value);
  }
</script>

How do I get the value from the text field into JavaScript?


Solution

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

Method 1

document.getElementById('textbox_id').value to get the value of desired box

For example

document.getElementById("searchTxt").value;

  Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use [1], and so on...

Method 2

Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example

document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.

Method 3

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example

document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

Method 4

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList

For example

document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.

Method 5

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element

For example

  • document.querySelector('#searchTxt').value; selected by id
  • document.querySelector('.searchField').value; selected by class
  • document.querySelector('input').value; selected by tagname
  • document.querySelector('[name="searchTxt"]').value; selected by name

Method 6

document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example

  • document.querySelectorAll('#searchTxt')[0].value; selected by id
  • document.querySelectorAll('.searchField')[0].value; selected by class
  • document.querySelectorAll('input')[0].value; selected by tagname
  • document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name

Support

Browser Method1 Method2 Method3 Method4 Method5/6
IE6 Y(Buggy) N Y Y(Buggy) N
IE7 Y(Buggy) N Y Y(Buggy) N
IE8 Y N Y Y(Buggy) Y
IE9 Y Y Y Y(Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N IE=Internet Explorer
FF3.5/FF3.6 Y Y Y Y Y FF=Mozilla Firefox
FF4b1 Y Y Y Y Y GC=Google Chrome
GC4/GC5 Y Y Y Y Y Y=YES,N=NO
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y(Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y

Useful links

  1. To see the support of these methods with all the bugs including more details click here
  2. Difference Between Static collections and Live collections click Here
  3. Difference Between NodeList and HTMLCollection click Here


Answered By - bugwheels94
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 4, 2022

[FIXED] How to parse response table with PHPExcel import Excel file to input tag (example : autofill input id="fname" to Hello and input id="lname" to World)?

 October 04, 2022     excel, html, html-input, php, phpexcel     No comments   

Issue

How to parse this response table with PHPExcel import Excel file into desired input fields (example : autofill input id="fname" to Hello and autofill input id="lname" to World)?

I can to

1. send file to PHP.

2. parse EXCEL file with third-party library (use PHPExcel library).

3. create response for AJAX/POST into HTML page.

but I can't parse this response table with PHPExcel import Excel file into desired input fields (example : autofill input id="fname" to Hello and autofill input id="lname" to World).

Sample code and file at the bottom.

  1. excelimport.xlsx (Excel file)

Download Link

  1. excelimport.php (PHP Code)
<!DOCTYPE html>
<html>
<head>
<style>
h2 {display: inline;}
</style>
<script>
var _validFileExtensions = [".xls", ".xlsx", ".csv"];    
function ValidateSingleInput(oInput) {
    if (oInput.type == "file") {
        var sFileName = oInput.value;
         if (sFileName.length > 0) {
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++) {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, 

sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    blnValid = true;
                    break;
                }
            }

            if (!blnValid) {
                alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", 

"));
                oInput.value = "";
                return false;
            }
        }
    }
    return true;
}
</script>
</head>
<body>

<?php
if(isset($_FILES['excel']) && $_FILES['excel']['error']==0) {
        require_once "PHPExcel/Classes/PHPExcel.php";
        $tmpfname = $_FILES['excel']['tmp_name'];
        $excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
        $excelObj = $excelReader->load($tmpfname);
        $worksheet = $excelObj->getSheet(0);
        $lastRow = $worksheet->getHighestRow();

        echo "<table class=\"table table-sm\">";
        for ($row = 1; $row <= $lastRow; $row++) {
             echo "<tr><td scope=\"row\">";
             echo $worksheet->getCell('A'.$row)->getValue();
             echo "</td><td>";
             echo $worksheet->getCell('B'.$row)->getValue();
             echo "</td><td>";
             echo $worksheet->getCell('C'.$row)->getValue();
             echo "</td><td>";
             echo $worksheet->getCell('D'.$row)->getValue();
             echo "</td><tr>";
        }
        echo "</table>";    
}
?>

<form action = "" method = "POST" enctype = "multipart/form-data">
    <h2 for="myfile1">Select files : </h2>
         <input type = "file" name = "excel" onchange="ValidateSingleInput(this)" />
         <input type = "submit"/><br><br>
</form>

    <h2 for="fname">First name : </h2><input type="text" id="fname" name="fname" 

value=""><br><br>
    <h2 for="lname">Last name : </h2><input type="text" id="lname" name="lname" 

value=""><br><br>
    <input type="submit" name="submit2">

</body>
</html>

I use PHPExcel library to download with link.


Solution

Good news : I have answer to parse response table with PHPExcel import Excel file to input tag (example : autofill input id=“fname” to Hello and input id=“lname” to World) with my full source code.

I have answer credit with link.

  1. excelimport.xlsx (Excel file)

Download Link

  1. excelimport.php (PHP Code)
<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>
    <style>
    h2 {display: inline;}
    </style>
</head>

<body>

<form action="" method="post" enctype="multipart/form-data" name="myform1" id="myform1">
    <h2 for="myfile1">Select files : </h2><input type="file" name="excelFile" id="excelFile" /><br><br>
    <h2 for="fname">First name : </h2><input type="text" id="fname" name="fname"><br><br>
    <h2 for="lname">Last name : </h2><input type="text" id="lname" name="lname"><br><br>
  <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     
<script type="text/javascript">
$(function(){


    // เมื่อฟอร์มการเรียกใช้ evnet submit ข้อมูล        
    $("#excelFile").on("change",function(e){
        e.preventDefault(); // ปิดการใช้งาน submit ปกติ เพื่อใช้งานผ่าน ajax

        // เตรียมข้อมูล form สำหรับส่งด้วย  FormData Object
       var formData = new FormData($("#myform1")[0]);

        // ส่งค่าแบบ POST ไปยังไฟล์ read_excel.php รูปแบบ ajax แบบเต็ม
        $.ajax({
            url: 'read_excel.php',
            type: 'POST',
            data: formData,
            /*async: false,*/
            cache: false,
            contentType: false,
            processData: false
        }).done(function(data){
                console.log(data);  // ทดสอบแสดงค่า  ดูผ่านหน้า console
/*              การใช้งาน console log เพื่อ debug javascript ใน chrome firefox และ ie 
                http://www.ninenik.com/content.php?arti_id=692 via @ninenik         */
                $("#fname").val(data.A2);
                $("#lname").val(data.B2);
        });     

    });


});
</script>
</body>
</html>
  1. read_excel.php (PHP Code)
<?php
header("Content-type:application/json; charset=UTF-8");    
header("Cache-Control: no-store, no-cache, must-revalidate");         
header("Cache-Control: post-check=0, pre-check=0", false); 
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Bangkok');
// http://php.net/manual/en/timezones.php
require_once("PHPExcel/Classes/PHPExcel.php");
?>
<?php 
if(isset($_FILES['excelFile']['name']) && $_FILES['excelFile']['name']!=""){
    $tmpFile = $_FILES['excelFile']['tmp_name'];  
    $fileName = $_FILES['excelFile']['name'];  // เก็บชื่อไฟล์
    $_fileup = $_FILES['excelFile'];
    $info = pathinfo($fileName);
    $allow_file = array("csv","xls","xlsx");
/*  print_r($info);         // ข้อมูลไฟล์   
    print_r($_fileup);*/
    if($fileName!="" && in_array($info['extension'],$allow_file)){
        // อ่านไฟล์จาก path temp ชั่วคราวที่เราอัพโหลด
        $objPHPExcel = PHPExcel_IOFactory::load($tmpFile);      


        // ดึงข้อมูลของแต่ละเซลในตารางมาไว้ใช้งานในรูปแบบตัวแปร array
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        // วนลูปแสดงข้อมูล
        $v=1;
        $json_data = array();
        foreach ($cell_collection as $cell) {
            // ค่าสำหรับดูว่าเป็นคอลัมน์ไหน เช่น A B C ....
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            // คำสำหรับดูว่าเป็นแถวที่เท่าไหร่ เช่น 1 2 3 .....
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            // ค่าของข้อมูลในเซลล์นั้นๆ เช่น A1 B1 C1 ....
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();          

            // เท่านี้เราก็สามารถแสดงข้อมูลจากการอ่านไฟล์ได้แล้ว และสามารถนำข้อมูลเหล่านี้
            // ทำการบันทักลงฐานข้อมูล หรือแสดงได้เลย
            $json_data["$column$row"] = $data_value;
//            echo $v." ----  ".$data_value."<br>";
             $v++;
        }       
         // แปลง array เป็นรูปแบบ json string  
        if(isset($json_data)){  
            $json= json_encode($json_data);    
            if(isset($_GET['callback']) && $_GET['callback']!=""){    
            echo $_GET['callback']."(".$json.");";        
            }else{    
            echo $json;    
            }    
        }        
    }
} 
?>

I use PHPExcel library to download with link.



Answered By - Sumate Mephokkij
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to fix code to manual select excel column at input id="selectcell1" and "selectcell2" (Ex : Select A2 in "selectcell1" to C2 in "selectcell2")?

 October 04, 2022     excel, html, html-input, php, phpexcel     No comments   

Issue

How to fix code to support manual select excel column at input id="selectcell1" and input id="selectcell2" (Example : Select A2 in input id="selectcell1" to select C2 in input id="selectcell2")?

I try to coding with sample code and file at the bottom (use code with credit at link).

  1. excelimport2.xlsx (Excel file)

Download Link

  1. excelimport.php (PHP Code)
<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>
    <style>
    h2,h4 {display: inline;}
    </style>
</head>

<body>

<form action="" method="post" enctype="multipart/form-data" name="myform1" id="myform1">

    <details>
        <summary>Input Excel cell to select.</summary>
        <br><h4 for="selectcell1">Excel cell to select at first : </h4><input type="text" id="selectcell1" name="selectcell1"><br><br>
        <h4 for="selectcell2">Excel cell to select at final : </h4><input type="text" id="selectcell2" name="selectcell2">
    </details><br>

    <h2 for="myfile1">Select files : </h2><input type="file" name="excelFile" id="excelFile" /><br><br>
    <h2 for="fname">First name : </h2><input type="text" id="fname" name="fname"><br><br>
    <h2 for="lname">Middle name : </h2><input type="text" id="lname" name="lname"><br><br>
    <h2 for="lname">Last name : </h2><input type="text" id="mname" name="mname"><br><br>
  <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     
<script type="text/javascript">
$(function(){


    // เมื่อฟอร์มการเรียกใช้ evnet submit ข้อมูล        
    $("#excelFile").on("change",function(e){
        e.preventDefault(); // ปิดการใช้งาน submit ปกติ เพื่อใช้งานผ่าน ajax

        // เตรียมข้อมูล form สำหรับส่งด้วย  FormData Object
       var formData = new FormData($("#myform1")[0]);

        // ส่งค่าแบบ POST ไปยังไฟล์ read_excel.php รูปแบบ ajax แบบเต็ม
        $.ajax({
            url: 'read_excel.php',
            type: 'POST',
            data: formData,
            /*async: false,*/
            cache: false,
            contentType: false,
            processData: false
        }).done(function(data){
                console.log(data);  // ทดสอบแสดงค่า  ดูผ่านหน้า console
/*              การใช้งาน console log เพื่อ debug javascript ใน chrome firefox และ ie 
                http://www.ninenik.com/content.php?arti_id=692 via @ninenik         */

                $('#selectcell1').val($('#selectcell1').val().toUpperCase());
                $('#selectcell2').val($('#selectcell2').val().toUpperCase());

                if($("#selectcell1").val() != ""){
                $("#fname").val(eval("data." + $("#selectcell1").val()));
                }
                if($("#selectcell2").val() != ""){
                $("#lname").val(eval("data." + $("#selectcell2").val()));
                }
                if($("#selectcell3").val() != ""){
                $("#mname").val(eval("data." + $("#selectcell3").val()));
                }
        });     
    });   
});
</script>
</body>
</html>
  1. read_excel.php (PHP Code)
<?php
header("Content-type:application/json; charset=UTF-8");    
header("Cache-Control: no-store, no-cache, must-revalidate");         
header("Cache-Control: post-check=0, pre-check=0", false); 
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Bangkok');
// http://php.net/manual/en/timezones.php
require_once("PHPExcel/Classes/PHPExcel.php");
?>
<?php 
if(isset($_FILES['excelFile']['name']) && $_FILES['excelFile']['name']!=""){
    $tmpFile = $_FILES['excelFile']['tmp_name'];  
    $fileName = $_FILES['excelFile']['name'];  // เก็บชื่อไฟล์
    $_fileup = $_FILES['excelFile'];
    $info = pathinfo($fileName);
    $allow_file = array("csv","xls","xlsx");
/*  print_r($info);         // ข้อมูลไฟล์   
    print_r($_fileup);*/
    if($fileName!="" && in_array($info['extension'],$allow_file)){
        // อ่านไฟล์จาก path temp ชั่วคราวที่เราอัพโหลด
        $objPHPExcel = PHPExcel_IOFactory::load($tmpFile);      


        // ดึงข้อมูลของแต่ละเซลในตารางมาไว้ใช้งานในรูปแบบตัวแปร array
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        // วนลูปแสดงข้อมูล
        $v=1;
        $json_data = array();
        foreach ($cell_collection as $cell) {
            // ค่าสำหรับดูว่าเป็นคอลัมน์ไหน เช่น A B C ....
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            // คำสำหรับดูว่าเป็นแถวที่เท่าไหร่ เช่น 1 2 3 .....
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            // ค่าของข้อมูลในเซลล์นั้นๆ เช่น A1 B1 C1 ....
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();          

            // เท่านี้เราก็สามารถแสดงข้อมูลจากการอ่านไฟล์ได้แล้ว และสามารถนำข้อมูลเหล่านี้
            // ทำการบันทักลงฐานข้อมูล หรือแสดงได้เลย
            $json_data["$column$row"] = $data_value;
//            echo $v." ----  ".$data_value."<br>";
             $v++;
        }       
         // แปลง array เป็นรูปแบบ json string  
        if(isset($json_data)){  
            $json= json_encode($json_data);    
            if(isset($_GET['callback']) && $_GET['callback']!=""){    
            echo $_GET['callback']."(".$json.");";        
            }else{    
            echo $json;    
            }    
        }        
    }
} 
?>

I use PHPExcel library to download with link.

But I can't to fix code to support manual select excel column at input id="selectcell1" and input id="selectcell2" (Example : Select A2 in input id="selectcell1" to select C2 in input id="selectcell2").


Solution

Good news : I have answer to support manual select horizontal excel cell at input id="selectcell1" and input id="selectcell2" (Example : Select A2 in input id="selectcell1" to select C2 in input id="selectcell2") with my full source code.

I have answer credit with link.

  1. excelimport3.xlsx (Excel file)

Download Link

  1. excelimport.php (PHP Code)
<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>
    <style>
    h2,h4 {display: inline;}
    </style>
</head>

<body>

<form action="" method="post" enctype="multipart/form-data" name="myform1" id="myform1">

    <details>
        <summary>Input Excel cell to select.</summary>
        <br><h4 for="selectcell1">Excel cell to select at first : </h4><input type="text" id="selectcell1" name="selectcell1"><br><br>
        <h4 for="selectcell2">Excel cell to select at final : </h4><input type="text" id="selectcell2" name="selectcell2"><br><br>
        <h4 for="selectcell1">Excel cell to select at first 2 : </h4><input type="text" id="selectcell3" name="selectcell3"><br><br>
        <h4 for="selectcell2">Excel cell to select at final 2 : </h4><input type="text" id="selectcell4" name="selectcell4">
    </details><br>

    <h2 for="myfile1">Select files : </h2><input type="file" name="excelFile" id="excelFile" /><br><br>
    <h2 for="fname">First name : </h2><input type="text" class="my-cssclass" id="fname" name="fname"><br><br>
    <h2 for="lname">Middle name : </h2><input type="text" class="my-cssclass" id="lname" name="lname"><br><br>
    <h2 for="lname">Last name : </h2><input type="text" class="my-cssclass" id="mname" name="mname"><br><br>
    <h2 for="fname">First name 2 : </h2><input type="text" class="my-cssclass2" id="fname2" name="fname2"><br><br>
    <h2 for="lname">Middle name 2 : </h2><input type="text" class="my-cssclass2" id="lname2" name="lname2"><br><br>
    <h2 for="lname">Last name 2 : </h2><input type="text" class="my-cssclass2" id="mname2" name="mname2"><br><br>
  <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     
<script type="text/javascript">
$(function(){


    // เมื่อฟอร์มการเรียกใช้ evnet submit ข้อมูล        
    $("#excelFile").on("change",function(e){
        e.preventDefault(); // ปิดการใช้งาน submit ปกติ เพื่อใช้งานผ่าน ajax

        // เตรียมข้อมูล form สำหรับส่งด้วย  FormData Object
       var formData = new FormData($("#myform1")[0]);

        // ส่งค่าแบบ POST ไปยังไฟล์ read_excel.php รูปแบบ ajax แบบเต็ม
        $.ajax({
            url: 'read_excel.php',
            type: 'POST',
            data: formData,
            /*async: false,*/
            cache: false,
            contentType: false,
            processData: false
        }).done(function(data){
                console.log(data);  // ทดสอบแสดงค่า  ดูผ่านหน้า console
/*              การใช้งาน console log เพื่อ debug javascript ใน chrome firefox และ ie 
                http://www.ninenik.com/content.php?arti_id=692 via @ninenik         */

        $('#selectcell1').val($('#selectcell1').val().toUpperCase());
        $('#selectcell2').val($('#selectcell2').val().toUpperCase());
        $('#selectcell3').val($('#selectcell3').val().toUpperCase());
        $('#selectcell4').val($('#selectcell4').val().toUpperCase());

        // จำลองค่าจาก input element เริ่มต้น และสิ้นสุด
        var cellStart = $("#selectcell1").val();
        var cellEnd = $("#selectcell2").val();

        var cellStart2 = $("#selectcell3").val();
        var cellEnd2 = $("#selectcell4").val();

        // ใช้คำสั่ง .replace() ตัดตัวเลขจากข้อความ เหลือไว้แค่ตัวอักษร
        var charStart = cellStart.replace(/[0-9]/,'');  // A
        var charEnd = cellEnd.replace(/[0-9]/,'');  // C
        // ใช้คำสั่ง .replace() ตัดตัวอักษรจากข้อความ แล้วแปลงข้อความที่เหลือเป็นตัวเลขด้วย parseInt()
        var rowNum = parseInt(cellStart.replace(/[A-Z]/,'')); // 2

        // ใช้คำสั่ง .replace() ตัดตัวเลขจากข้อความ เหลือไว้แค่ตัวอักษร
        var charStart2 = cellStart2.replace(/[0-9]/,'');  // A
        var charEnd2 = cellEnd2.replace(/[0-9]/,'');  // C
        // ใช้คำสั่ง .replace() ตัดตัวอักษรจากข้อความ แล้วแปลงข้อความที่เหลือเป็นตัวเลขด้วย parseInt()
        var rowNum2 = parseInt(cellStart2.replace(/[A-Z]/,'')); // 2

        // ฟังก์ชั่นสร้าง array range ตัวอย่าง เช่น range("A","C")  จะได้ ["A","B","C"];
        function range(start,stop) {
            var result=[];
            for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
            result.push(String.fromCharCode(idx));
        }
        return result;
        };

        // วนลูป Array ตัวอักษร เพื่อใช้ อ้างอิงข้อมูล
        range(charStart, charEnd).map((value, key) => {
            console.log("data." + value + rowNum);
            var dataValue = eval("data." + value + rowNum);
            $(".my-cssclass").eq(key).val(dataValue);
        });

        // วนลูป Array ตัวอักษร เพื่อใช้ อ้างอิงข้อมูล
        range(charStart2, charEnd2).map((value2, key2) => {
            console.log("data." + value2 + rowNum2);
            var dataValue2 = eval("data." + value2 + rowNum2);
            $(".my-cssclass2").eq(key2).val(dataValue2);
        });

        });     
    });   
});
</script>
</body>
</html>
  1. read_excel.php (PHP Code)
<?php
header("Content-type:application/json; charset=UTF-8");    
header("Cache-Control: no-store, no-cache, must-revalidate");         
header("Cache-Control: post-check=0, pre-check=0", false); 
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Bangkok');
// http://php.net/manual/en/timezones.php
require_once("PHPExcel/Classes/PHPExcel.php");
?>
<?php 
if(isset($_FILES['excelFile']['name']) && $_FILES['excelFile']['name']!=""){
    $tmpFile = $_FILES['excelFile']['tmp_name'];  
    $fileName = $_FILES['excelFile']['name'];  // เก็บชื่อไฟล์
    $_fileup = $_FILES['excelFile'];
    $info = pathinfo($fileName);
    $allow_file = array("csv","xls","xlsx");
/*  print_r($info);         // ข้อมูลไฟล์   
    print_r($_fileup);*/
    if($fileName!="" && in_array($info['extension'],$allow_file)){
        // อ่านไฟล์จาก path temp ชั่วคราวที่เราอัพโหลด
        $objPHPExcel = PHPExcel_IOFactory::load($tmpFile);      


        // ดึงข้อมูลของแต่ละเซลในตารางมาไว้ใช้งานในรูปแบบตัวแปร array
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        // วนลูปแสดงข้อมูล
        $v=1;
        $json_data = array();
        foreach ($cell_collection as $cell) {
            // ค่าสำหรับดูว่าเป็นคอลัมน์ไหน เช่น A B C ....
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            // คำสำหรับดูว่าเป็นแถวที่เท่าไหร่ เช่น 1 2 3 .....
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            // ค่าของข้อมูลในเซลล์นั้นๆ เช่น A1 B1 C1 ....
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();          

            // เท่านี้เราก็สามารถแสดงข้อมูลจากการอ่านไฟล์ได้แล้ว และสามารถนำข้อมูลเหล่านี้
            // ทำการบันทักลงฐานข้อมูล หรือแสดงได้เลย
            $json_data["$column$row"] = $data_value;
//            echo $v." ----  ".$data_value."<br>";
             $v++;
        }       
         // แปลง array เป็นรูปแบบ json string  
        if(isset($json_data)){  
            $json= json_encode($json_data);    
            if(isset($_GET['callback']) && $_GET['callback']!=""){    
            echo $_GET['callback']."(".$json.");";        
            }else{    
            echo $json;    
            }    
        }        
    }
} 
?>

I use PHPExcel library to download with link.

Extra : I have answer to support manual select vertical excel cell at input id="selectcell1" and input id="selectcell2" (Example : Select A2 in input id="selectcell1" to select A4 in input id="selectcell2") and support number more than 10 with my full source code.

I have answer credit with link.

  1. excelimport3.xlsx (Excel file)

Download Link

  1. excelimport.php (PHP Code)
<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>
    <style>
    h2,h4 {display: inline;}
    </style>
</head>

<body>

<form action="" method="post" enctype="multipart/form-data" name="myform1" id="myform1">

    <details>
        <summary>Input Excel cell to select.</summary>
        <br><h4 for="selectcell1">Excel cell to select at first : </h4><input type="text" id="selectcell1" name="selectcell1"><br><br>
        <h4 for="selectcell2">Excel cell to select at final : </h4><input type="text" id="selectcell2" name="selectcell2"><br><br>
        <h4 for="selectcell1">Excel cell to select at first 2 : </h4><input type="text" id="selectcell3" name="selectcell3"><br><br>
        <h4 for="selectcell2">Excel cell to select at final 2 : </h4><input type="text" id="selectcell4" name="selectcell4">
    </details><br>

    <h2 for="myfile1">Select files : </h2><input type="file" name="excelFile" id="excelFile" /><br><br>
    <h2 for="fname">First name : </h2><input type="text" class="my-cssclass" id="fname" name="fname"><br><br>
    <h2 for="lname">Middle name : </h2><input type="text" class="my-cssclass" id="lname" name="lname"><br><br>
    <h2 for="lname">Last name : </h2><input type="text" class="my-cssclass" id="mname" name="mname"><br><br>
    <h2 for="fname">First name 2 : </h2><input type="text" class="my-cssclass2" id="fname2" name="fname2"><br><br>
    <h2 for="lname">Middle name 2 : </h2><input type="text" class="my-cssclass2" id="lname2" name="lname2"><br><br>
    <h2 for="lname">Last name 2 : </h2><input type="text" class="my-cssclass2" id="mname2" name="mname2"><br><br>
  <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     
<script type="text/javascript">
$(function(){


    // เมื่อฟอร์มการเรียกใช้ evnet submit ข้อมูล        
    $("#excelFile").on("change",function(e){
        e.preventDefault(); // ปิดการใช้งาน submit ปกติ เพื่อใช้งานผ่าน ajax

        // เตรียมข้อมูล form สำหรับส่งด้วย  FormData Object
       var formData = new FormData($("#myform1")[0]);

        // ส่งค่าแบบ POST ไปยังไฟล์ read_excel.php รูปแบบ ajax แบบเต็ม
        $.ajax({
            url: 'read_excel.php',
            type: 'POST',
            data: formData,
            /*async: false,*/
            cache: false,
            contentType: false,
            processData: false
        }).done(function(data){
                console.log(data);  // ทดสอบแสดงค่า  ดูผ่านหน้า console
        /*  การใช้งาน console log เพื่อ debug javascript ใน chrome firefox และ ie 
                http://www.ninenik.com/content.php?arti_id=692 via @ninenik  */

        $('#selectcell1').val($('#selectcell1').val().toUpperCase());
        $('#selectcell2').val($('#selectcell2').val().toUpperCase());
        $('#selectcell3').val($('#selectcell3').val().toUpperCase());
        $('#selectcell4').val($('#selectcell4').val().toUpperCase());

        // จำลองค่าจาก input element เริ่มต้น และสิ้นสุด แบบแนวตั้งครับ
        var cellStart = $("#selectcell1").val();
        var cellEnd = $("#selectcell2").val();

        var cellStart2 = $("#selectcell3").val();
        var cellEnd2 = $("#selectcell4").val();

        // ใช้คำสั่ง .replace() ตัดตัวอักษรจากข้อความ แล้วแปลงข้อความที่เหลือเป็นตัวเลขด้วย parseInt() 
        var minV = parseInt(cellStart.replace(/[A-Z]/,'')); // ได้ค่าเริ่มต้นตัวเลข สมมติ "A2" จะได้เป็น 2
        var maxV = parseInt(cellEnd.replace(/[A-Z]/,''));   // ได้ค่าสิ้นสุดตัวเลข สมมติ "A5" จะได้เป็น 5

        // ใช้คำสั่ง .replace() ตัดตัวเลขจากข้อความ เหลือไว้แค่ตัวอักษร
        var colChar = cellEnd.replace(/[0-9]+/,''); // สมมติ "A5" จะได้เป็น A

        // ใช้คำสั่ง .replace() ตัดตัวอักษรจากข้อความ แล้วแปลงข้อความที่เหลือเป็นตัวเลขด้วย parseInt()
        var minV2 = parseInt(cellStart2.replace(/[A-Z]/,'')); // ได้ค่าเริ่มต้นตัวเลข สมมติ "A2" จะได้เป็น 2
        var maxV2 = parseInt(cellEnd2.replace(/[A-Z]/,''));   // ได้ค่าสิ้นสุดตัวเลข สมมติ "A5" จะได้เป็น 5

        // ใช้คำสั่ง .replace() ตัดตัวเลขจากข้อความ เหลือไว้แค่ตัวอักษร
        var colChar2 = cellEnd2.replace(/[0-9]+/,''); // สมมติ "A5" จะได้เป็น A

        var idx = 0;
        var idx2 = 0;

        // วนลูปเพื่ออ้างอิงตำแหน่ง property ของ object ตามช่วงข้อมูล
        for ( var c = minV; c <= maxV; c++){
            console.log("data." + colChar + c); // จะได้ค่า เป็น "data.A2" , "data.A3"... "data.A5");
            var dataValue = eval("data." + colChar + c);
            $(".my-cssclass").eq(idx).val(dataValue);
            idx++;
        } 

        // วนลูปเพื่ออ้างอิงตำแหน่ง property ของ object ตามช่วงข้อมูล
        for ( var c2 = minV2; c2 <= maxV2; c2++){
            console.log("data." + colChar2 + c2); // จะได้ค่า เป็น "data.A2" , "data.A3"... "data.A5");
            var dataValue2 = eval("data." + colChar2 + c2);
            $(".my-cssclass2").eq(idx2).val(dataValue2);
            idx2++;
        }

        });     
    });   
});
</script>
</body>
</html>
  1. read_excel.php (PHP Code)
<?php
header("Content-type:application/json; charset=UTF-8");    
header("Cache-Control: no-store, no-cache, must-revalidate");         
header("Cache-Control: post-check=0, pre-check=0", false); 
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Bangkok');
// http://php.net/manual/en/timezones.php
require_once("PHPExcel/Classes/PHPExcel.php");
?>
<?php 
if(isset($_FILES['excelFile']['name']) && $_FILES['excelFile']['name']!=""){
    $tmpFile = $_FILES['excelFile']['tmp_name'];  
    $fileName = $_FILES['excelFile']['name'];  // เก็บชื่อไฟล์
    $_fileup = $_FILES['excelFile'];
    $info = pathinfo($fileName);
    $allow_file = array("csv","xls","xlsx");
/*  print_r($info);         // ข้อมูลไฟล์   
    print_r($_fileup);*/
    if($fileName!="" && in_array($info['extension'],$allow_file)){
        // อ่านไฟล์จาก path temp ชั่วคราวที่เราอัพโหลด
        $objPHPExcel = PHPExcel_IOFactory::load($tmpFile);      


        // ดึงข้อมูลของแต่ละเซลในตารางมาไว้ใช้งานในรูปแบบตัวแปร array
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        // วนลูปแสดงข้อมูล
        $v=1;
        $json_data = array();
        foreach ($cell_collection as $cell) {
            // ค่าสำหรับดูว่าเป็นคอลัมน์ไหน เช่น A B C ....
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            // คำสำหรับดูว่าเป็นแถวที่เท่าไหร่ เช่น 1 2 3 .....
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            // ค่าของข้อมูลในเซลล์นั้นๆ เช่น A1 B1 C1 ....
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();          

            // เท่านี้เราก็สามารถแสดงข้อมูลจากการอ่านไฟล์ได้แล้ว และสามารถนำข้อมูลเหล่านี้
            // ทำการบันทักลงฐานข้อมูล หรือแสดงได้เลย
            $json_data["$column$row"] = $data_value;
//            echo $v." ----  ".$data_value."<br>";
             $v++;
        }       
         // แปลง array เป็นรูปแบบ json string  
        if(isset($json_data)){  
            $json= json_encode($json_data);    
            if(isset($_GET['callback']) && $_GET['callback']!=""){    
            echo $_GET['callback']."(".$json.");";        
            }else{    
            echo $json;    
            }    
        }        
    }
} 
?>

I use PHPExcel library to download with link.



Answered By - Sumate Mephokkij
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing