I'm trying to upload a spreadsheet and read it into a MySQL database using PHPExcel.
For .xlsx files it works fine but whenever I try to upload a .ods file it throws the error: PHP Fatal error: Call to a member function getNamespaces() on a non-object in PHPExcel_1.7.9/Classes/PHPExcel/Reader/OOCalc.php on line 341
What's going wrong?
HTML Form:
<form method="post" enctype="multipart/form-data">
Upload File: <input type="file" name="spreadsheet"/>
<input type="submit" name="submit" value="Submit" />
</form>
PHP (In same file):
//Check valid spreadsheet has been uploaded
if(isset($_FILES['spreadsheet'])){
if($_FILES['spreadsheet']['name']){
if(!$_FILES['spreadsheet']['error'])
{
$inputFile = $_FILES['spreadsheet']['name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if($extension == 'XLSX' || $extension == 'ODS'){
//Read spreadsheeet workbook
try {
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch(Exception $e) {
die($e->getMessage());
}
//Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//Insert into database
}
}
else{
echo "Please upload an XLSX or ODS file";
}
}
else{
echo $_FILES['spreadsheet']['error'];
}
}
}
?>
When a file is uploaded to your webserver, The file will be saved in the temporary folder of your system with a random name.
What you were trying to do was giving the actual name of the file you uploaded, But since the file was created with a random name in the tmp folder.
You will need to use tmp_name instead, Which actually point the that random named file.
Also note, in name You only have the name of the file that was uploaded and not the path,
But with tmp_name you have the actual path to the file.
See the following example of a file upload you would get.
array(
[UploadFieldName]=>array(
[name] => MyFile.jpg
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174
)
)
change your code to this instead
//Check valid spreadsheet has been uploaded
if(isset($_FILES['spreadsheet'])){
if($_FILES['spreadsheet']['tmp_name']){
if(!$_FILES['spreadsheet']['error'])
{
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if($extension == 'XLSX' || $extension == 'ODS'){
//Read spreadsheeet workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch(Exception $e) {
die($e->getMessage());
}
//Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//Insert into database
}
}
else{
echo "Please upload an XLSX or ODS file";
}
}
else{
echo $_FILES['spreadsheet']['error'];
}
}
}
?>
In my case there was an error detecting the extension in this line
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if you need to solve just check from the name parameter
$extension = strtoupper(explode(".", $_FILES['spreadsheet']['name'])[1]);
The rest is working thanks :)
Related
I got a problem when call the PHPExcel library AutoLoader.php file.
I try to upload the Excel file, then after clicking on the upload button, it saves data into the database. I get an error, as shown in the photo after uploading the file. How can I fix this?
<?php
require('library/Classes/PHPExcel/IOFactory.php');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
if(isset($_POST['submit'])){
if((isset($_POST['file'])) && !empty($_POST['file']))
{
$file = $_POST['file'];
}
$fileName= $_FILES["file"]["name"];
echo ('fileName +'.$fileName);
//$uploadPath = $_SERVER['DOCUMENT_ROOT'].'/SMS/excel/' ;
$fileTempName= $_FILES["name"]["temp_name"];
//echo ('fileTempName +'.$fileTempName);
$fileExtension= pathinfo($fileName,PATHINFO_EXTENSION);
$allowedtype= array('xlsx','sls','xlsm');
if(!in_array($fileExtension,$allowedtype)){
echo("<br/>Sorry, File type is not allowed. Only Excel file.");
}
else {
echo("Correct File Extension");
try
{
$inputfiletype = PHPExcel_IOFactory::identify($fileName);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($fileName);
echo 'Reading the number of Worksheets in the WorkBook<br />';
/** Use the PHPExcel object's getSheetCount() method to get a count of the number of WorkSheets in the WorkBook */
$sheetCount = $objPHPExcel->getSheetCount();
echo 'There ',(($sheetCount == 1) ? 'is' : 'are'),' ',$sheetCount,' WorkSheet',(($sheetCount == 1) ? '' : 's'),' in the WorkBook<br /><br />';
echo 'Reading the names of Worksheets in the WorkBook<br />';
/** Use the PHPExcel object's getSheetNames() method to get an array listing the names/titles of the WorkSheets in the WorkBook */
$sheetNames = $objPHPExcel->getSheetNames();
foreach($sheetNames as $sheetIndex => $sheetName) {
echo 'WorkSheet #',$sheetIndex,' is named "',$sheetName,'"<br />';
}
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($fileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
}
}
?>
I tried to read a .csv file using the PHPExcel library but it is giving me question marks instead of the Hebrew text.
The problem only occur when I tried to upload .csv files created from Windows Operating System. I tried the same for MacOS and Linux and the data seems to be fine. How can I solve the encoding issue from windows
public function actionUpload()
{
$params = $_FILES['uploadFile'];
if($params)
{
$data = array();
$model = new UploadForm();
$model->uploadFile = $_FILES['uploadFile'];
$file = UploadedFile::getInstanceByname('uploadFile');
$inputFileName = $model->getpath($file,$data);
// Read your Excel workbook
try
{
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName['link']);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName['link']);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName['link'],PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$fileData = array();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
array_push($fileData,$rowData[0]);
// Insert row data array into your database of choice here
}
return $fileData;
}
}
The output array has "???? ???" in places where Hebrew text was present when .csv files created from Windows was uploaded.
I am facing a problem in a project which is uploading excel file through using the CodeIgniter3 and PHPExcel library.
The problem occurs when I upload an excel file, the file is uploaded successfully into the folder but it cannot be read. Further, it gives an error message:
Error loading file "xls_file": Could not open file ./assets/xls_file/ for reading.
So the data couldn't be saved into the database.
I want the system read the file inside the folder of xls_file, why is the system reading the xls_file as folder? My friend told me there may be problem in the URI in CodeIgniter 3, but we don’t know the solution how to fix the problem. Here’s my controller :
$fileName = time().$_FILES['file']['name'];
$config['upload_path'] = './assets/xls_file/'; //save excel file in folder
$config['file_name'] = $fileName;
$config['allowed_types'] = 'xls|xlsx|csv';
$config['max_size'] = 10000;
$this->load->library('upload');
$this->upload->initialize($config);
if(! $this->upload->do_upload('file') )
$this->upload->display_errors();
$media = $this->upload->data('file');
$inputFileName = './assets/xls_file/'.$media['file_name'];
try {
$inputFileType = IOFactory::identify($inputFileName);
$objReader = IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++){ // Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
//save into the column
$data = array(
"id_jalan"=> $rowData[0][0],
"id_kriteria"=> $rowData[0][1],
"nilai"=> $rowData[0][2],
"tahun_anggaran"=> $rowData[0][3],
"penanda"=> $rowData[0][4],
);
//save into the tabel
$insert = $this->db->insert("value",$data);
//delete_files($media['file_path']);
}
redirect('page/landing');
Trying to allow the user to select a browsed excel file from their computer. Take that excel file and parse through it then write the data to a database. I am having trouble getting the parse to work. I know I need to use...
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" id="uploadedfile" /> <br />
<input type="submit" value="Upload File" />
and my only question is that when I use the $_FILES["uploadedfile"]["name"] it only gives me the filename and not the directory of the file so how can I pass this to PHPExcel Reader. Isn't this just a string of the filename and not actually a file path?
Heres what I have in my uploader.php:
<?php
include ('/PHPExcel/Classes/PHPExcel/IOFactory.php');
$filename = $_FILES["uploadedfile"]['name'];
echo $filename;
$inputFileType = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader -> load($filename);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$data = array();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$data[] = $rowdata;
// Insert row data array into your database of choice here
}
foreach ($data as $param){
echo $param;
}
?>
You'll need the temporary name to either read it or move it to a place of your choosing:
print_r($_FILES);
Point the path directly and pass it to IOFactory:
$filename = $_FILES["uploadedfile"]['name'];
$fullFilename = PROJECT_DIR . 'upload/' . $filename;
$inputFileType = PHPExcel_IOFactory::identify($fullFilename);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader -> load($fullFilename);
iam need to load excelsheet data into database using codeigiter.for that i have tried this coding
function excel_data()
{
//include 'PHPExcel/IOFactory.php';
$this->load->library("PHPExcel");
$inputFileName = '../first_data.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
// $this->User_model->add_data($rowData);
}
}
while executing iam getting this error "Error loading file "first_data.xls": Could not open ../first_data.xls for reading! File does not exist." what is the problem in my coding.
what is my mistake.did anyone knows that?