I am using the excelToArray function found here: https://gist.github.com/calvinchoy/5821235
function excelToArray($filePath, $header = true) {
require_once("./PHPExcel/Classes/PHPExcel.php"));
//Create excel reader after determining the file type
$inputFileName = $filePath;
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Set read type to read cell data onl **/
// $objReader->setReadDataOnly(true); removed because: https://stackoverflow.com/questions/46142706/
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
//Get worksheet and built array with first row as header
$objWorksheet = $objPHPExcel->getActiveSheet();
//excel with first row header, use header as key
if($header){
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
}
else{
//excel sheet with no header
$namedDataArray = $objWorksheet->toArray(null,true,true,true);
}
return $namedDataArray;
}
I have a sample spreadsheet in Excel. Here it is:
Preview: https://drive.google.com/open?id=0B2GilRTNrTzKRUVsQWhnQkRLUmM
Direct Download: https://drive.google.com/uc?authuser=0&id=0B2GilRTNrTzKRUVsQWhnQkRLUmM&export=download
The problem is that when I upload the spreadsheet I'm seeing that phone numbers (which are simply large integers (ex: 2345556789) in the spreadsheet I am provided) are coming in with [<=9999999] in front of them. Ex: [<=9999999]1393153-7665
What is causing this and how I do get it to simple read it in as an string (or even an int)?
Related
I use phpexcel to read a table,but sometimes it can't get value which is not empty.
import('ORG.PHPExcel');
import('ORG.PHPExcel.IOFactory');
import('ORG.PHPExcel.Reader.Excel5');
import('PHPExcel.Reader.Excel2007');
$objReader = new PHPExcel_Reader_Excel5();
$objReader->setReadDataOnly(true);
//use excel2007
$objPHPExcel = new PHPExcel();
$objPHPExcel = $objReader->load($uploadfile);
$sheet = $objPHPExcel->getSheet(1);
$highestRow = $sheet->getHighestRow();
var_dump($highestRow);
$highestColumn = $sheet->getHighestColumn();
var_dump($highestColumn);
$count=0;
$zzdw = M('zzdw');
for($j=4;$j<=$highestRow;$j++)
{
$count++;
$flag=0;
$b= (string)$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
if($b==''){
echo('<font color="red"><strong>'.$count.'</strong></font>');
var_dump($b);
exit;
}
}
result
like this, row and col have value,but can't get cell's value.
some files don't have this problem,some have.
file format error?I use ".xls".
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'm trying to read an excel.xlsx file. But I just can't, I'm reading about an API called PHPExcel but I can't make it work. This is what I tried:
<?php
// get access to the class
require_once 'Classes/PHPExcel.php';
include 'Classes/IOFactory.php';
$inputFileName = 'teste.xlsx';
// 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);
echo $rowData[$row];
}
?>
at the end of the for loop, I tried to read or echo the data, but I got errors like: Undefined offset.
I am using PHPExcel to only read values from excel sheets
if i use this code , it works fine without no problem:
function ReadUploadedFile($Uploadedfile,$fileExtension)
{
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '')
{
// Read rows 1 to 7 and columns A to E only
if ($row>=1 && $row<=100) {
if (in_array($column,range('A','Z'))) {
return true;
}
}
return false;
}
}
}
$filterSubset = new MyReadFilter();
$inputFileType="";
$inputFileType = 'Excel5';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadFilter($filterSubset);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load('myExcelsheet.xls');
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$sheetData now is an array and i can use it with no problem.
what if i have many worksheets ,and i need to specify only one , as per documentation from PHPEXCEL , they say to use setLoadSheetsOnly()
i try the code blow but it doesn't work.
$inputFileType = 'Excel2007';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadFilter($filterSubset);
$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly("Summary"); //my worksheet name is Summary
$objPHPExcel = $objReader->load('myExcelsheet.xlsx');
so what should i write after the above line to convert this object to Array
i try this
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
but it gives this error
Call to a member function cellExists() on a non-object
and when i try this
$sheetData = $objPHPExcel->toArray(null,true,true,true);
Call to undefined method PHPExcel::toArray()
/** Here is my code work: */
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br/>');
/** PHPExcel_IOFactory */
require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$inputFileType = 'Excel2007';
$inputFileName = 'file.xlsx';
$sheetname = 'mysheey'; // I DON'T WANT TO USE SHEET NAME HERE
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly($sheetname);
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
echo ' Highest Column ' . $getHighestColumn = $objPHPExcel->setActiveSheetIndex()->getHighestColumn(); // Get Highest Column
echo ' Get Highest Row ' . $getHighestRow = $objPHPExcel->setActiveSheetIndex()->getHighestRow(); // Get Highest Row
echo "<pre>";
print_r($sheetData);
echo "</pre>";
Work for me.
I'm using: rangeToArray();
"phpoffice/phpspreadsheet": "^1.3"
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load('report.xlsx');
$worksheet = $spreadsheet->setActiveSheetIndex(0);
$highestRow = $worksheet->getHighestRow();
$highestCol = $worksheet->getHighestColumn();
print_r($worksheet->rangeToArray("A4:$highestCol$highestRow", null, true, false, false));
// If you want to format data e.g. 2450 to 2,450
// You could set rangeToArray parameter at 4 = true
I am trying to read just one sheet from an xls document and I have this:
$objPHPExcel = $objReader->load('daily/' . $fisierInbound);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
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);
$dataCalls = $worksheet->getCellByColumnAndRow(2, 2)->getValue();
$dataSubstr = substr($dataCalls, 53);
}
The problem is that it reads all the sheets of the file.
Any ideas?
As described in the PHPExcel User Documentation - Reading Spreadsheet Files document in the /Documentation folder (section 5.2. entitled"Reading Only Named WorkSheets from a File"):
If you know the name of the sheet that you want to read.
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetname = 'Data Sheet #2';
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Advise the Reader of which WorkSheets we want to load **/
$objReader->setLoadSheetsOnly($sheetname);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
If you don't know the name of the worksheet in advance, you can get a list of all worksheets before loading the file
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Read the list of worksheet names and select the one that we want to load **/
$worksheetList = $objReader->listWorksheetNames($inputFileName)
$sheetname = $worksheetList[0];
/** Advise the Reader of which WorkSheets we want to load **/
$objReader->setLoadSheetsOnly($sheetname);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
You can do it easier than getting list of worksheet names:
$objPHPExcel->setActiveSheetIndex(2);
$worksheet = $objPHPExcel->getActiveSheet();
Loads #2 (third) worksheet.
An easiest way for those who is still struggling with this -
//include library
include('path/to/PHPExcel/IOFactory.php');
//load the file
$objPHPExcel = PHPExcel_IOFactory::load('your/path/for/excel/file');
//get the worksheet of your choice by its name
$worksheet = $objPHPExcel->getSheetByName('Name of sheet');
#and your work goes here...
//load library - EXCEL
$this->load->library('excel');
$objPHPExcel = PHPExcel_IOFactory::load('./folder/exceldata.xls');
Individual worksheets can be accessed by name, or by their index position in the workbook. The index position represents the order that each worksheet "tab" is shown when the workbook is opened in MS Excel (or other appropriate Spreadsheet program).
To access a sheet by name, use the getSheetByName() method, specifying the name of the worksheet that you want to access.
//Retrieve the worksheet called 'Worksheet 1'
$objPHPExcel->getSheetByName('Worksheet 1');
To access a sheet by its index, use the getSheet() method.
Note that sheets are indexed from 0.
//Retrieve the **1st 'tab' worksheet** e.g. called 'Sheet 1'
$worksheet = $objPHPExcel->getSheet(0);
//Retrieve the **2nd 'tab' worksheet** e.g. called 'Sheet 2'
$worksheet = $objPHPExcel->getSheet(1);
This all can be achieved by help of #Mark Baker 's PHPExcel Library. Thanks.
// In CodeIgniter Version - 3.1.11
public function upload(){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
if(isset($_FILES["file_upload"]["name"]))
{
require 'vendor/autoload.php';
$path = $_FILES["file_upload"]["tmp_name"];
$object = PHPExcel_IOFactory::load($path);
$db_flag = true;
foreach($object->getWorksheetIterator() as $worksheet)
{
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$sheetname = $worksheet->getTitle();
$sheetname = trim($sheetname);
if ($sheetname == "Asset Wise & Location Wise")
{
$db_flag = false;
$db_count = 0;
$this->db->truncate("fi_asset_wise");
$this->load->helper('dt_helper');
$this->db->trans_start();
// get data from excel
for($row=5; $row<=$highestRow; $row++)
{
$asst_categ = trim($worksheet->getCellByColumnAndRow(0, $row)->getCalculatedValue());
if(empty($asst_categ) || strpos(strtoupper($asst_categ), "TOTAL") !== FALSE )
{
continue;
}
$descrip = trim($worksheet->getCellByColumnAndRow(1, $row)->getCalculatedValue());
$rate = trim($worksheet->getCellByColumnAndRow(2, $row)->getCalculatedValue());
$main_head = trim($worksheet->getCellByColumnAndRow(3, $row)->getCalculatedValue());
$sub_head = trim($worksheet->getCellByColumnAndRow(4, $row)->getCalculatedValue());
$gl_code = trim($worksheet->getCellByColumnAndRow(5, $row)->getCalculatedValue());
$asset_code = trim($worksheet->getCellByColumnAndRow(6, $row)->getCalculatedValue());
if(empty($dt_of_sale)) {
$dt_of_sale = null;
}else{
$db_udt = ($dt_of_sale- 25569) * 86400;
$date=date("d-m-Y", $db_udt);
$dt_of_sale = check_format_method($date);
}
$no_of_days = trim($worksheet->getCellByColumnAndRow(26, $row)->getCalculatedValue());
$insert_arr = array(
'asst_categ' => $asst_categ,
'descrip' => $descrip,
'rate' => $rate,
'main_head' => $main_head,
'sub_head' => $sub_head,
'gl_code' => $gl_code,
'asset_code' => $asset_code,
'dt_of_sale' => $dt_of_sale,
'no_of_days' => ($no_of_days >= 0.00 )?$no_of_days:0.00,
'status' => 1,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
if(!empty($insert_arr))
{
$this->ass_model->insertData($insert_arr);
++$db_count;
}
}
$this->db->trans_complete();
// Running Transactions Manually
if ($this->db->trans_status() === FALSE){
$this->db->trans_rollback();
} else {
$this->db->trans_commit();
}
}
}
if($db_flag === true)
{
$this->session->set_flashdata('db_error', 'Error !! Invalid Sheet Name. Please enter correct sheetname.');
redirect(site_url('fixed-asset/fixed-asset-register'));
}
if($db_count > 0)
{
$this->session->set_flashdata('db_success', 'Success - Data Inserted Successfully');
redirect(site_url('fixed-asset/fixed-asset-register'));
}
}
}