Create Excel Files With Number Format Settings In PHP Using PHPSpreadSheet

Create a spreadsheet and format the display of numbers accordingly, add a thousand comma separator, guarantee that the output will always have a certain number of decimal places, are some of the number format settings that can be achieved when coding an xlsx file in PhpSpreadsheet.

Requirements:

  • 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.

<?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 "12345.6" string value
$sheet->setCellValue('A1', '12345.6');

// Set cell A2 with the "123456" string value
$sheet->setCellValue('A2', '123456');

// Set cell A3 with the "123.456" string value
$sheet->setCellValue('A3', '123.456');

/**
 * Set cell A1 to cell A3 style format to 'number'
 * with thousand comma separator, and two decimal places
 */
$sheet->getStyle('A1:A3')->getNumberFormat()->setFormatCode('#,##0.00');

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

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

Test.

Run the following codes.

$ php create-xlsx-files-with-number-format-settings.php

Result.

Open the generated file create-xlsx-files-with-number-format-settings.xlsx.

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

// Set cell A2 with the "123456" string value
$sheet->setCellValue('A2', '123456');

// Set cell A3 with the "123.456" string value
$sheet->setCellValue('A3', '123.456');

/**
 * Set cell A1 to cell A3 style format to 'number'
 * with thousand comma separator, and two decimal places
 */
$sheet->getStyle('A1:A3')->getNumberFormat()->setFormatCode('#,##0.00');

Click on Format -> Format Cells

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Leave a Reply

Your email address will not be published. Required fields are marked *