PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 4, 2022

[FIXED] How to copy cell values into other empty cells of a csv file in php?

 October 04, 2022     excel, php, php-7, phpexcel     No comments   

Issue

I have a csv file that contains several empty cells like this : enter image description here

I would like every time the value in the 'Style' column changes that the empty cells take the values of the same style, like this: enter image description here

I don't really see how I will be able to proceed to put the expected values in the cells, if someone could help me it would be a great help...

<?php

//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_file.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);

// Excel in CSV
$excel = PHPExcel_IOFactory::load($xlsx);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$nomcsv = "C:/wamp64/www/Extract_pictures_Excel/csv/".date('Ymd_His').".csv";
$writer->save($nomcsv);

$delimiter = ";"; 
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        //I tried this for if this value changes put back the old ones 
        $data = $data[5] ?: $data[5];
        $csv_data[] = $data;
        $row++;      
    }
    fclose($handle);
}

if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}


?>

Solution

You need to keep track of the previous style, a simple way would be to set it to blank initially and if the element is blank - set it from the previous style. Note that you only should be updating that element of the array (so add [5] to the assignment)...

$prevData = [];
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
    // Overlay current values over the previous values
    $data = array_replace ( $prevData, array_filter($data));
    // Store current data for future use
    $prevData = $data;
    $csv_data[] = $data;
    $row++;
}


Answered By - Nigel Ren
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing