This following code simply ignore all empty cells in my excelsheet.
Is there any way to read empty cell or replace them to "Null" values?
See the code here---https://arjunphp.com/how-to-use-phpexcel-with-codeigniter/
$file = './files/test.xlsx';
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
$maxCell = $objPHPExcel->getHighestRowAndColumn();
$newdata = array();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
I tried this following code
$newdata = $objPHPExcel->rangeToArray($cell . $maxCell['column'] . $maxCell['row']);
$newdata = array_map('array_filter', $data);
$newdata = array_filter($data);
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
//send the data in an array format
$data['header'] = $header;
$data['values'] = $arr_data;
print_r($newdata);
Get this error messgae... Fatal error: Call to undefined method PHPExcel::getHighestRowAndColumn()
you're try to wrong way, in this way you only get the last active cell value and if you try to get empty cell cell value in middle you're not able to get value. and you use some PhpSpreadsheet function and also some time you try get value using class object. check your code one more time.
Related
I'm looking to upload a CSV, compare the first column with a database and remove if it matches and output a new CSV.
Example of CSV:
tel,name,email
07777777777,Harry,harry#gmail.com
07777777788,Paul,paul#gmail.com
Example of database:
tel name email
07777777777 Harry Harry,harry#gmail.com
End result of CSV file:
tel,name,email
07777777788,Paul,paul#gmail.com
I found example on here, but tried to amend it. Code so far:
if(isset($_POST['submit'])){
require_once('db-config.php');
$input_filename = $_FILES['file']['tmp_name'];
$output_filename = 'output.csv';
$input_file = fopen($input_filename, 'r');
$output_file = fopen($output_filename, 'w');
$tels = array();
$query = "SELECT tel FROM people";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$tels[] = $row['tels'];
}
// Read the header
$headers = fgetcsv($input_file, 10000);
fputcsv($output_file, $headers);
// Deleted rows counter
$rows_deleted = 0;
// Read every row
while($row = fgetcsv($input_file, 10000) !== FALSE) {
$tel = $row[$headers['tel']];
// Do we already have this tel?
if(isset($tels, $tel)){
// row skipped - therefore it is deleted
$rows_deleted++;
continue;
}
// Mark this tel as being found
$tels[$tel]= true;
// Write it to the output
fputcsv($output_file, $row);
}
fclose($input_file);
fclose($output_file);
// Now we should move output file to input one
echo "Deleted: " . $rows_deleted;
}
Your $tels array is a list of telehone numbers so the isset() wont work as the array will look like this for example, so replace that with in_array()
[0] 07777777777
[1] 07777777779
Also the fgetcsv() returns numeric array of the comman seperated content of a line so the telephone will be $row[0]
while( ($row = fgetcsv($input_file, 10000) ) !== FALSE) {
// change below
$tel = $row[0];
// Do we already have this tel?
if(in_array($tel, $tels)){
// row skipped - therefore it is deleted
$rows_deleted++;
continue;
}
// this tel does not exist, so write to new csv
fputcsv($output_file, $row);
// this tel wont exist in the $tels array?
// so not sure what you are doing this for ??
// and of course the array does not look like that the keys are
// numeric increments
// Mark this tel as being found
//$tels[$tel]= true;
}
i need to have the csv have the format of the first picture but im currently getting the second picture as a final result, how can i set it properly so MailChimp can read the csv properly
$jsonDecoded = json_decode(file_get_contents('emails.json', true), true);
$list = array(
array('Email Address', 'First Name')
);
$timestamp = time();
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[$timestamp] = $new;
}
//if old file exist delete
$fp = fopen('emails.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Desired Output
Current Output with the above code
The main Issue I can see is you are overwriting the same field in the array, because you are using the same key in the loop
//$timestamp = time(); - only set once, won't change
foreach($jsonDecoded as $entry)
{
// this will update, but won't produce a different key for each iteration,
// because the loop might be faster than the smallest precision
// that the time() function can produce
$timestamp = time();
$new = array($entry['email'], $entry['name']);
$list[$timestamp] = $new;
}
I don't see a use for the timestamp itself, so I suggest just use array_push() or the shorthand shown below
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[] = $new; // this just adds the element to the end of the array
}
I need to read excel as calculated value when cell of excel contains formula.
Example: "=+VLOOKUP(A3,#REF!,2,0)", "=966+955+988+818+700+660+573"
Problem: PHPExecel reads formula in result and i want calculated values from excel.
Please help and see link for my code.
I'm using PHPExcel-1.8
https://github.com/PHPOffice/PHPExcel/tree/1.8/Classes
Im getting error as
https://ibb.co/cHb2Kb
if(file_exists($file_path)){
//load the excel library
$CI->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file_path);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
if(strstr($data_value,'=')==true){
// $data_value = $objPHPExcel->getActiveSheet()->getCalculatedValue($cell)->getValue();
}
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
//send the data in an array format
$data['header'] = $header;
$data['values'] = $arr_data;
return $data;
}
Consider using the cell's getCalculatedValue() method for cells containing formulae rather than simply getValue(); or trying to call getCalculatedValue() against the worksheet.
This is described in the PHPExcel Documentation.....
it's as simple as
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getCalculatedValue();
not anything even remotely like
$data_value = $objPHPExcel->getActiveSheet()->getCalculatedValue($cell)->getValue();
I have csv file with 1500+ entries in a column.I can able to read csv file's all values of column with this.
$rowcount = 1;
$srcFileName = "input/test.csv";
$file = fopen($srcFileName,"r");
$inputfielscount = count(file($srcFileName, FILE_SKIP_EMPTY_LINES));
while($rowcount < $inputfielscount)
{
$row = fgetcsv($file);
$result=array("id" =>$row[0],"des"=>"I am jhon",salery="10000");
$Final=array("listingsEmp"=>$result);
}
After reading first (1-10) value i will create an array (like array [0] =>$result) and Then wantto repeat same task from (11-20) and create another array (like array [1] =>$Final this time $final array contain information about the next ids whic we read from csv file (11-10)) and so on.
For the above requirment i changed code to this :
$rowcount = 1;
$srcFileName = "input/test.csv";
$file = fopen($srcFileName,"r");
while($rowcount < 20)
{
if(($rowcount % 10 == 0) && ( $rowcount != 0)) {
$rowcount++;
break;
}else{
$row = fgetcsv($file);
// some curl code for fetching data according to csv file field(Id)
$result=array("id" =>$row[0],"des"=>"I am jhon",salery="10000"); //contain 10 array
}
}
$Final=array("listingsEmp"=>$result);
Now i will post this $final array which has (0-10 index array ,each has unique id and corresponding values) using curl and get response which i am save in csv file.
$currenttime=date("Y-m-d-H_i_s");
$opfile='output'.$currenttime.'.csv'; //path wher op csv file exist
if(!#copy($srcFileName,'/output/'.$opfile))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}else { // echo "File copied from remote!";
$fp = fopen('output/output'.$currenttime.'.csv',"a");
$fr = fopen($srcFileName,"r");
$rowcounts=0;
$FinalRES=$Final->response;
while($rowcounts< $inputfielscount) {
$resultBulk=$FinalRES[$rowcounts];
$resultBulkStatus=$FinalRES->status;
$resultBulkErrors=$FinalRES->errors;
$errorMsgArray=$resultBulkErrors[0];
$BulkErrorsMessage=$errorMsgArray->message;
$rows = fgetcsv($fr);
if($resultBulkStatus=='failure'){
$list = array ($rows[0],$rows[1],$resultBulkStatus,$BulkErrorsMessage);
}else {
$list = array ($rows[0],$rows[1],$resultBulkStatus,"successfully");
}
fputcsv($fp,$list);
//$p++;
$rowcounts++;
}
}
This full code runs once and give response for 10 ids ,i want repeat this code again for next 10 id (11-20)and then for (21-30) so on .
Once all response write in output csv file After that it display download output file link,Output file contain full response for all Ids which is in csv file(1500 +)
<?php $dnldfilw='output'.$currenttime.'.csv';?>
<a href='download.php?filename=<?php echo $dnldfilw; ?>'>Download Output file</a>
?>
The easiest method is to just use the file() function you are already using...
So to shorten the code to some pseudocode:
<?php
$indexedArray = array();
$indexedSplit = 10;
$lines = file($srcFileName);
$tempArray = array();
foreach($lines as $line) {
if(count($tempArray) % $indexedSplit === 0) {
$indexedArray[] = $tempArray;
$tempArray = array();
}
$tempArray[] = $line;
}
foreach($indexedArray as $index => $valueArray) {
// do the curl magic
// write results of curl into csv
}
Your question is poorly phrased, but I think this would be your aim, right?
When reading a sheet with phpExcel using the toArray method, hidden rows are also parsed.
Is there a method I can use before toArray to remove hidden rows?
Code so far, using Codeigniter
$this->load->library('excel');
$objPHPExcel = PHPExcel_IOFactory::load($upload_data['full_path']);
foreach ($objPHPExcel->getAllSheets() as $sheet) {
$sheets[$sheet->getTitle()] = $sheet->toArray();
}
$data = array();
foreach ($sheets['Data'] as $key => $row) {
if ($key > 0) {
$item = array();
$item['name'] = $row[1];
$item['code'] = $row[2];
$data[] = $item;
}
}
When converting the sheet to Array using PHPExcel_Worksheet::toArray you will get all of the rows, regardless if they are visible or not.
If you want to filter only the visible rows you will have to iterate over the rows and check for each of them if they are visible or not. You can check the visibility of a row using
$sheet->getRowDimension($row_id)->getVisible()
$row_id starts with 1 (and not 0), same is in excel
Here is an example of how to use it in your code. I changed a bit the way you get the Data sheet, since you don't need to iterate over the sheets, you can just get that specific sheet using the getSheetByName function.
$data_sheet = $objPHPExcel->getSheetByName('Data');
$data_array = $data_sheet->toArray();
$data = [];
foreach ($data_sheet->getRowIterator() as $row_id => $row) {
if ($data_sheet->getRowDimension($row_id)->getVisible()) {
// I guess you don't need the Headers row, note that now it's row number 1
if ($row_id > 1) {
$item = array();
$item['name'] = $data_array[$row_id-1][1];
$item['code'] = $data_array[$row_id-1][2];
$data[] = $item;
}
}
}