Create Excel Files With Explicit Cell Datatype In PHP Using PHPSpreadSheet

Explicitly set a cell’s datatype when creating an xslx file with 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 a "1" numeric value
$sheet->getCell('A1')->setValueExplicit(
    '1',
    \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC
);

// Set cell A2 with a "True" boolean value
$sheet->getCell('A2')->setValueExplicit(
    true,
    \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_BOOL
);

// Set cell A4 with a "Hello World !" string value with datatype numeric
/*$sheet->getCell('A4')->setValueExplicit(
    "Hello World !",
    \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC
);*/

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

// Save the new .xlsx file
$writer->save('create-xlsx-files-with-explicit-cell-datatype.xlsx');

Test.

Run the following codes.

$ php create-xlsx-files-with-explicit-cell-datatype.php

Result.

Open the generated file create-xlsx-files-with-explicit-cell-datatype.xlsx.

// Set cell A1 with a "1" numeric value
$sheet->getCell('A1')->setValueExplicit(
    '1',
    \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC
);

// Set cell A2 with a "True" boolean value
$sheet->getCell('A2')->setValueExplicit(
    true,
    \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_BOOL
);

Test Again.

Try to set a string cell value and set it’s datatype to numeric.

$sheet->getCell('A4')->setValueExplicit(
    "Hello World !",
    \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC
);

Will return a fatal error since “Hello World !” is a string, and not a numeric value.

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 *