Phpspreadsheet: Zero is saved as empty string in excel files

Created on 5 Apr 2018  路  4Comments  路  Source: PHPOffice/PhpSpreadsheet

This is:

- [x] a bug report

What is the expected behavior?

Add 0 as a value to cells.

What is the current behavior?

Adds '' instead of 0 to cells. (ex. discount_price is saved as '' instead of 0 in the below code)

What are the steps to reproduce?

<?php

require __DIR__ . '/vendor/autoload.php';

// Create new Spreadsheet object
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();

$data = [
  "name" => "Prod 1"
  "category" => "Category 7"
  "sku" => "SKU-PROD-1"
  "price" => 19
  "discount_price" => 0
  "stock" => 78
  "description" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eu nulla lectus. Pellentesque lectus odio, ultrices in aliquet dignissim, aliquet in dolor. Mauris efficitur magna sapien, eget auctor lacus aliquam et. Proin ac blandit leo. Donec facilisis mauris eu turpis eleifend, et tincidunt nisl interdum. Curabitur massa diam, mollis et commodo ut, vehicula eu tortor."
  "group_sku" => "GROUP-SKU-1"
  "secondary_category" => "Category 1"
  "images" => ""
  "attribute1" => ""
  "attribute2" => ""
  "attribute3" => ""
  "attribute4" => ""
  "attribute5" => ""
  "extra1" => "Extra 7"
  "extra2" => ""
  "extra3" => "Extra 8"
  "extra4" => "Extra 2"
  "extra5" => "Extra 4"
];

 $spreadsheet->getActiveSheet()->fromArray($data);
 $writer = new Xlsx($spreadsheet);
 $writer->save(public_path($this->file));

Which versions of PhpSpreadsheet and PHP are affected?

PhpSpreadsheet 1.2.0
PHP 7.0

Most helpful comment

$spreadsheet->getActiveSheet()->fromArray($data, null, 'A1', true);

Adding this solves the problem.

All 4 comments

$spreadsheet->getActiveSheet()->fromArray($data, null, 'A1', true);

Adding this solves the problem.

The behavior described is the intended behavior. This is not a bug, but a feature and is correctly described in API: https://github.com/PHPOffice/PhpSpreadsheet/blob/bdc95b14bf51015a3b82d73dd0d5934359b85484/src/PhpSpreadsheet/Worksheet/Worksheet.php#L2473

is correctly described in API

..but not the documentation.

This feature should be described here:
https://phpspreadsheet.readthedocs.io/en/latest/topics/accessing-cells/#setting-a-range-of-cells-from-an-array
..where the example already has a zero value and includes input and output screenshots.

Adding true at the end didn't work for me.

By the way, does anyone else find this unnecessarily verbose?

fromArray($array, [value that stands for a blank cell], 'A1', [yes, we really mean it]);

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AlexPravdin picture AlexPravdin  路  4Comments

stratboy picture stratboy  路  5Comments

emeraldjava picture emeraldjava  路  4Comments

sadlyblue picture sadlyblue  路  3Comments

isopen picture isopen  路  3Comments