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');
Related
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 want to read the data of .xlsx or .xls file in codeigniter. I have read the other questions related it but nothing works. I have used phpexcel, reader but with no luck. In my project i give the option to upload excel file then i want to read the data and insert it in the database.
Now i am using phpExcel library I have wrote:
$this->load->library('excel');
$reader= PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path=(FCPATH.'uploads/productfile/'.$_FILES['upload_file']['name']);
$excel=$reader->load($path);
$sheet=$excel->setActiveSheetIndex(0);
for($i=0;$i<=1000;$i++)
{
$col1= $sheet->getCellByColumnAndRow(0,$i)->getValue();
$col2= $sheet->getCellByColumnAndRow(1,$i)->getValue();
$col3= $sheet->getCellByColumnAndRow(2,$i)->getValue();
var_dump($col1);
}
but it display :
Uncaught exception 'PHPExcel_Exception' with message 'You tried to set
a sheet active by the out of bounds index: 0. The actual number of
sheets is 0 Please give me some example code.
The error
Please give me some example code:
Try this :
$sheet = $excel->getActiveSheet()->toArray(null,true,true,true);
This will return you an array of the current active sheet.Hope this helps.
This error is caused by a wrong initialization of the PHPexcel reader functionalities I suppose.
I usually do something like this to get the data from an excel:
require_once '../Classes/PHPExcel/IOFactory.php';
$filename = '../uploads/product/abc.xls';
$objPHPExcel = PHPExcel_IOFactory::load($filename);
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);
$nrColumns = ord($highestColumn) - 64;
$total_rows = $highestRow-1;
for ($row = 2; $row <= $highestRow; ++ $row) {
//id
$cell = $worksheet->getCellByColumnAndRow(0,$row);
$id = $cell->getValue();
if(is_null($id)){$id = '#';}
}
Thanks to all for your suggestion:
I got the solution :
$file_data = $this->upload->data();
$file_path = './uploads/productfile/'.$file_data['file_name'];
include 'Classes/PHPExcel/IOFactory.php';
$inputFileName = $file_path;
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
'product'=$allDataInSheet[$i]["C"],
'brand'=$allDataInSheet[$i]["I"],
'standard'=$allDataInSheet[$i]["J"],
}
This extension of PHPExcel_IOFactory has issues with symbols like ™ Trademark, Copy Right, Degree etc.
You can't read a particular block if it contains such special characters.
This code segment works for me,
$this->load->library('excel');
$reader= PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path= "./media/customer_exports/data-1558003506.xlsx";
$excel=$reader->load($path);
$sheet = $excel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($sheet);
for($i=2;$i<=$arrayCount;$i++)
{
echo $sheet[$i]["A"].$sheet[$i]["B"].$sheet[$i]["C"];
}
I am trying to upload a csv file after then the file data will be print/insert.But my code is not printing the data according to my code.It is printing Id: Marks complete 1.But my file is uploading.
my input csv file format is
Id,Marks
20,46
20,46
32,45
My controller code is
public function upload_marks(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '10000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('marksfile'))
{
echo $this->upload->display_errors();
}
else
{
$uploadData = $this->upload->data();
$fileName = $uploadData['file_name'];
$this->load->library('csvreader');
$csvData = $this->csvreader->parse_file('./uploads/',$fileName);
foreach($csvData as $data){
echo " ID: ".$data['id'];
echo " Marks: ".$data['marks'];
}
echo " Complete 1";
}
}
Where is the problem ? Could you get my error ?
Suppose your data is in B1,B2,B3,B4 position for your excell sheet, Then code as given below with phpexcel library.
$uploadData = $this->upload->data();
$fileName = $uploadData['file_name'];
$this->load->library('excel');
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load('./uploads/'.$fileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$prof = $objPHPExcel->getActiveSheet()->getCell('B1')->getValue();
$term = $objPHPExcel->getActiveSheet()->getCell('B2')->getValue();
$sbjCode = $objPHPExcel->getActiveSheet()->getCell('B3')->getValue();
$year = $objPHPExcel->getActiveSheet()->getCell('B4')->getValue();
After then code as above for your rest data according to position. Hope this will works .
Use PHPExcel Library it works fantastic, I have used same in various projects.
https://phpexcel.codeplex.com/
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 :)
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?