phpexcellaravelphpexcel

how to set different font sizes within in a cell


$rowIndex = 1;
foreach ($request->warehouses as $warehouse) {
    $whId = $warehouse['id_warehouse'];
    $warehouse = Warehouse::find($whId);
    if ($warehouse) {
            foreach ($rowDetails as $rowDetail) {
                $fieldName = $rowDetail['id_field'];
                $fieldValue = $warehouse->$fieldName;
                $fontSize = $rowDetail['font_size'];
                $cellData = "$fieldValue\n";
                $sheet->setCellValue('A' . $rowIndex, $cellData);
                $sheet->getStyle('A' . $rowIndex)->getAlignment()->setWrapText(true);
                $sheet->getStyle('A' . $rowIndex)->getFont()->setSize($fontSize);
                
                $rowIndex++;
            }
        
    }
}

In this code, field_value has a different font_size and is separated in each cell:

result

I want to make an export excel file with format where each field_value has a font_size value that has been set and the field_values are separated by a new line in the cell (wrap text), while the new data from each warehouses will be separated in a new cell. For example like this:

expectations


Solution

  • To set different font sizes within a single cell and separate field_values by a new line (wrap text) in the cell, you can use the RichText feature provided by PHPExcel.

    foreach ($rowDetails as $rowDetail) {
        $fieldName = $rowDetail['id_field'];
        $fieldValue = $warehouse->$fieldName;
        $fontSize = $rowDetail['font_size'];
        $richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
        $textRun = $richText->createTextRun($fieldValue);
        $textRun->getFont()->setSize($fontSize);
        $cellData = $richText;
        $sheet->setCellValue('A' . $rowIndex, $cellData);
        $sheet->getStyle('A' . $rowIndex)->getAlignment()->setWrapText(true);
    
        $rowIndex++;
    }