SpreadSheet-Coding.com

PhpSpreadsheet

Create Excel Files With Text Wrap Settings In PHP Using PHPSpreadSheet

August 3, 2020

Fit all data in it’s specific cell to display all cell information without overflowing to the other cell boundaries by making use of the function setWrapText() when coding to create an xlsx file in PhpSpreadsheet. Doing this will auto adjust the row height depending on the cell contents, thus, avoiding any confusion reading any cell details when having all the data in just a single line.

Requirements:

Step 1.

Setup dependencies.

composer.json
{
    "require": {
        "phpoffice/phpspreadsheet": "^1.3"
    }
}

Step 2.

Install phpspreadsheet.

command line
$ composer install

Step 3.

Create a new PHP file, and start coding.

create-xlsx-files-with-text-wrap-settings.php
<?php

// Autoload dependencies
require 'vendor/autoload.php';

// Import the core class of PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;

// Import the Xlsx writer class
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();

// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();

// Set cell A1 with the "Hello World ! Hello World ! Hello World !" string value
$sheet->setCellValue('A1', 'Hello World ! Hello World ! Hello World !');

// Set 'wrap text' option to cell A1 
$sheet->getStyle('A1')->getAlignment()->setWrapText(true);

// Write a new .xlsx file
$writer = new Xlsx($spreadsheet);

// Save the new .xlsx file
$writer->save('create-xlsx-files-with-text-wrap-settings.xlsx');

Test.

Run the following codes.

command line
$ php create-xlsx-files-with-text-wrap-settings.php

Result.

Open the generated file create-xlsx-files-with-text-wrap-settings.xlsx.

PHP
// Set cell A1 with the "Hello World ! Hello World ! Hello World !" string value
$sheet->setCellValue('A1', 'Hello World ! Hello World ! Hello World !');

// Set 'wrap text' option to cell A1 
$sheet->getStyle('A1')->getAlignment()->setWrapText(true);

Default.

References: