I'm using PHP Excel to create an Excel using a template Excel file. The problem is I have a datagrid and which I styled the header and first row in template. Here how it looks like:
The top leftmost coordinate is C49.
If I have 100 rows, I need to copy style of first row and paste it 100 times. Here is my code
$cstart = 2;
$rstart = 49;
$count = 1;
$input = $worksheet->getStyle(num2char($cstart) . $rstart);
foreach ($b_data['rawData'] as $value) {
$worksheet->setCellValueByColumnAndRow($cstart, $rstart, $count++)
->setCellValueByColumnAndRow($cstart + 1, $rstart, $value['key'])
->setCellValueByColumnAndRow($cstart + 5, $rstart, $value['value']);
$interval = num2char($cstart) . $rstart . ':' . num2char($cstart+5) . $rstart;
$worksheet->duplicateStyle($input, $interval);
$rstart++;
}
function num2char($num) {
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
return num2char($num2 - 1) . $letter;
} else {
return $letter;
}
}
However, I had the following:
but what I expected is:
Is it bug or am I doing something wrong?
Select the cell with the formatting you want to copy. Select Home > Format Painter. Drag to select the cell or range you want to apply the formatting to. Release the mouse button and the formatting should now be applied.
Select Format > Copy Style (from the Format menu at the top of your screen). Select other text where you want to apply the style, or place the insertion point in text, then select Format > Paste Style.
Ctrl+Alt+V, A This shortcut will paste all of the formatting from your source data, including the borders. So, if your source data has bold text and a yellow background, those formatting features will be applied to the destination cells.
As Mark pointed out in the comments; a merged cell is structural, not style. So copying the style will not automatically copy the merged cells.
There is a feature request to be able to duplicate entire rows including merged cells
One way to deal with this is to check if the cells are part of a merge using the isInMergeRange()
function like this:
$workbook = new PHPExcel; // prepare the workbook
$sheet = $workbook->getActiveSheet(); // get the sheet
$sheet->mergeCells('A1:E1'); // merge some cells for tesing
$cell = $sheet->getCell('A1'); // get a cell to check if it is merged
$cell->isInMergeRange() // check if cell is merged
^This returns a Boolean value indicating if it is part of a merged cell.
Another function that may interest you is the isMergeRangeValueCell()
function:
$cell->isMergeRangeValueCell()
^This returns a Boolean value indicating it is part of a merged cell and the cell contains the value for the merged range; it returns false in all other situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With