简体   繁体   中英

How to import excel file using phpexcel and ajax?

I have a problem in importing the excel file using PHPExcel, when im trying to import, there is a fatal error: Couldn't open 'filename.xls', File does not exist. How can i solve this? This is my code so far.

javascript / Ajax uploading file:

function load_file(id,url,type,data,json,callback) {
    var xmlhttp;    
    var fdata = new FormData();
    fdata.append('SelectedFile', data);

    (window.XMLHttpRequest)?xmlhttp = new XMLHttpRequest():xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState==4 && xmlhttp.status==200) {  
            ((id != "")?(document.getElementById(id).innerHTML = xmlhttp.responseText):(((json == true)?(callback(JSON.parse(xmlhttp.responseText))):(callback(xmlhttp.responseText)))));
        }
    }

    xmlhttp.open(type,url,true);

    if(type == "POST") {
        xmlhttp.send(fdata);
    } else {
        xmlhttp.send();
    }   
}

load_file("","../../../phpscript/management/import_excel.php","POST",subNavigationAidToolFileInput.files[0],false,function(data) {
    alert(data);
});

PHP:

/* Database Connection */
include_once "../global/db_connect.php";

require "../../resources/widgets/PHPExcel_1.8.0_doc/Classes/PHPExcel.php";
require_once "../../resources/widgets/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php";

$Connection = new connection();

$objPHPExcel = PHPExcel_IOFactory::load($_FILES['SelectedFile']['name']);

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
     $worksheetTitle = $worksheet->getTitle();
     $highestRow = $worksheet->getHighestRow(); // e.g. 10
     $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
     $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
}

echo $_FILES['SelectedFile']['name'];

$_FILES['SelectedFile']['name'] is a reference to the filename not the file itself.

php stores the uploaded file to a temporary location defined in your php.ini

You can then move it and save it to a permanent location which is what I recommend you do before you attempt to access it/parse it via PHPExcel.

Here's a reference:

http://php.net/manual/en/features.file-upload.post-method.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM