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
Related
I want to merge 2 or more excel with PhpSpreadsheet. I'm trying to keep the styles for each sheet, this is my code:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$inputFileType = 'Xlsx';
$inputFileNames = [
'a.xlsx',
'b.xlsx',
'c.xlsx'
];
$sheetnames = [
'Worksheet',
'Worksheet1',
'Worksheet2'
];
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$inputFileName = array_shift($inputFileNames);
$spreadsheetMain = $reader->load($inputFileName);
$spreadsheetMain->getActiveSheet()->setTitle('page0');
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getActiveSheet()->setTitle($inputFileName[0]);
$clonedWorksheet->setTitle('page' . $contador);
$spreadsheetMain->addSheet($clonedWorksheet);
$contador++;
}
$writer = new Xlsx($spreadsheetMain);
$writer->save('prueba1.xlsx');
to do what I want, I need to change this
$spreadsheetMain->addSheet($clonedWorksheet);
for that $spreadsheetMain->addExternalSheet($clonedWorksheet);
But when I execute that code I get the error: 'Sheet does not exist'
I tought it's not still implemented, but is here in the documentation page: https://phpspreadsheet.readthedocs.io/en/develop/topics/worksheets/#copying-worksheets
Here you can download my excels and code for try if you want:
https://drive.google.com/open?id=1qkI8jdYDuA6e5CW6z3k0r_7j1pTvW_6D
The problem with addExternalSheet was that I needed to name both sheets (the original that I load and the cloned Sheet) with the same name. (All files are here : https://drive.google.com/open?id=1qkI8jdYDuA6e5CW6z3k0r_7j1pTvW_6D, mergeSolved is the correct file) This is the code with the solution:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$inputFileType = 'Xlsx';
$inputFileNames = [
'a.xlsx',
'b.xlsx',
'c.xlsx'
];
$sheetnames = [
'Worksheet',
'Worksheet1',
'Worksheet2'
];
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$inputFileName = array_shift($inputFileNames);
$spreadsheetMain = $reader->load($inputFileName);
$spreadsheetMain->getActiveSheet()->setTitle('page0');
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getSheetByName('Worksheet'.$contador);
$clonedWorksheet->setTitle('Worksheet'.$contador);
$spreadsheetMain->addExternalSheet($clonedWorksheet);
$contador++;
}
$writer = new Xlsx($spreadsheetMain);
$writer->save('prueba1.xlsx');`
require 'vendor/autoload.php';
$lists = [
'flie_01.xlsx',
'flie_02.xlsx'
];
$outfile='/tmp/merge.xlsx';
$merge_spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$merge_spreadsheet->getProperties()->setCreator("act");
foreach($lists as $file){
if(!file_exists($file)){
continue;
}
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file);
foreach($spreadsheet->getSheetNames() as $sheet_name ){
$clonedWorksheet = clone $spreadsheet->getSheetByName($sheet_name);
$clonedWorksheet->setTitle($sheet_name);
$merge_spreadsheet->addSheet($clonedWorksheet);
}
}
$merge_spreadsheet->removeSheetByIndex(0);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet,'Xlsx');
$writer->save($outfile);
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 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)?
I am building a script that takes every xls file from the /uploads folder and converts it to CSV.
But, I am having this error:
Fatal error:
Uncaught Error: Call to undefined function convertXLStoCSV() in C:\xampp\htdocs\Technocripa-php\scandir.php:46 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Technocripa-php\scandir.php on line 46
Here is the code:
$dir = "uploads/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
//--------------------------
$nameAsString = (string)$file;
require_once('Classes/PHPExcel.php');
$inputfilename = $nameAsString;
$outputfilename = 'convert.csv';
//Usage:
convertXLStoCSV($inputfilename, $outputfilename);
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
}
I think the error comes from wrong variable usage, but I really can't find a way to fix this. All I want to is store the name of te file in the uploads/ folder in a variable and use it throughout my script.
Here's the program without the LOOP, it works without any errors. Maybe it helps to understand better.
require_once('Classes/PHPExcel.php');
$inputfilename = 'test2.xls';
$outputfilename = 'convert.csv';
//Usage:
convertXLStoCSV($inputfilename, $outputfilename);
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
Create the function outside of foreach and call it inside like below:
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
$dir = "uploads/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
//--------------------------
$nameAsString = (string)$file;
require_once('Classes/PHPExcel.php');
$inputfilename = $nameAsString;
$outputfilename = 'convert.csv';
//Usage:
convertXLStoCSV($inputfilename, $outputfilename);
}
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
convertXLStoCSV($inputfilename, $outputfilename);
declare the function before using it
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'));
}
}
}