Ohidul Islam
Ohidul Islam

Reputation: 57

how write in phpspreadsheet cell by using loop

I would like to make phpspreadsheet like enter image description here I've tried below code

   foreach( range('A','C') as $ro) { 
        $r= $ro . "4";    
    $sheet->setCellValue($r,'Sn');
    $sheet->setCellValue($r,'Name');
    $sheet->setCellValue($r,'Title');
    }

but it shows as enter image description here

So, How can get my desired excel sheet

Upvotes: 0

Views: 2185

Answers (1)

Daniel
Daniel

Reputation: 11172

Is there a reason you don't just do it without a loop?

$sheet->setCellValue('A4','Sn');
$sheet->setCellValue('B4','Name');
$sheet->setCellValue('C4','Title');

The problem is that for every iteration in your foreach loop, you are replacing the value of the same cell.

In first iteration, we will have $r = 'A4'. Then you set A4 to "Sn". After that you set A4 to "Name" and then you set A4 to "Title". By then, you've replaced the content of the same cell 3 times for this iteration.

So it's best to skip the loop.

If you insist on looping, you could introduce logic that maps specific columns to specific values, but unless you have other specific logic involved, it is really overcomplicating the solution


If you want to loop because of many column names, I suggest you loop over an array of columns. If you use a normal array it will be zero-indexed, which means you can map it to the appropriate character with the chr() function by adding 65 to the index. Note that this will only work for 26 columns or less.

$columns = ['Sn', 'Name', 'Title'];

foreach ($columns as $index => $column) {
  $cell = chr($index + 65) . "4";

  $sheet->setCellValue($cell, $column);
}

You can also use an associative array and have the column be the key of the array - this would work for any amount of columns (but you still have to define the map)

$columns = [
  'A' => 'Sn',
  'B' => 'Name',
  'C' => 'Title'
];

foreach ($columns as $index => $column) {
  $sheet->setCellValue($index."4", $column);
}

Upvotes: 1

Related Questions