Create Xlsx Files With Column Width Settings

| September 5, 2020 | 1,467 views | PhpSpreadsheet

Adjust a selected column width when creating an xlsx file using PhpSpreadsheet, estimate the maximum number of characters from a given column and code the value of it’s width to fit the data on it’s designated cell.


  • Composer
  • PHP 7.2 or newer

Step 1.

Setup dependencies.

    "require": {
        "phpoffice/phpspreadsheet": "^1.3"

Step 2.

Install phpspreadsheet.

$ composer install

Step 3.

Create a new PHP file, and start coding.


// 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 !" string value
$sheet->setCellValue('A1', 'Hello World !');

// Set column A width to 20 character units

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

// Save the new .xlsx file


Run the following codes.

$ php create-xlsx-files-with-column-width-settings.php


Open the generated file create-xlsx-files-with-column-width-settings.xlsx.

// Set column A width to 20 character units




Leave a Reply

Your email address will not be published.