How to Work with Cells Core API in PHP

How to Work with Cells Core API in PHP

Workbook is the entry point for every task in Aspose.Cells FOSS for PHP. This guide walks through creating a workbook, writing data, styling it, saving, and reloading it with repair options enabled.

Step-by-Step Guide

Step 1: Install the Package

git clone https://github.com/aspose-cells-foss/Aspose.Cells-FOSS-for-PHP.git
cd Aspose.Cells-FOSS-for-PHP
composer install

Step 2: Import Required Classes

use Aspose\Cells_FOSS\Color;
use Aspose\Cells_FOSS\FillPattern;
use Aspose\Cells_FOSS\Workbook;

Step 3: Create a Workbook and Write Data

$workbook = new Workbook();
$sheet = $workbook->Worksheets[0];

$sheet->Name = 'Products';
$sheet->Cells['A1']->PutValue('Product');
$sheet->Cells['B1']->PutValue('Price');
$sheet->Cells['A2']->PutValue('Apple');
$sheet->Cells['B2']->PutValue(2.99);
$sheet->Cells['A3']->PutValue('Orange');
$sheet->Cells['B3']->PutValue(1.99);
$sheet->Cells['B4']->Formula = '=SUM(B2:B3)';

Step 4: Style a Cell

$headerStyle = $sheet->Cells['A1']->GetStyle();
$headerStyle->Font->IsBold = true;
$headerStyle->Font->Color = Color::FromArgb(255, 255, 255, 255);
$headerStyle->Pattern = FillPattern::Solid;
$headerStyle->ForegroundColor = Color::FromArgb(255, 34, 120, 212);

$sheet->Cells['A1']->SetStyle($headerStyle);

Step 5: Save the Workbook

$workbook->Save('products.xlsx');

Step 6: Reload with Repair Options

use Aspose\Cells_FOSS\LoadOptions;

$loadOptions = new LoadOptions();
$loadOptions->TryRepairPackage = true;
$loadOptions->TryRepairXml = true;

$reloaded = new Workbook('products.xlsx', $loadOptions);
if ($reloaded->LoadDiagnostics->HasDataLossRisk) {
    echo 'Potential data loss risk detected during load.' . PHP_EOL;
}

Common Issues and Fixes

Save() throws on an unwritable path. Confirm the destination directory exists and the PHP process has write permission before calling Save().

A reloaded formula shows a stale value. Aspose.Cells FOSS for PHP does not calculate formulas — open the file in Excel or LibreOffice, which recalculates on open.

GetStyle() changes don’t appear on the saved file. Cell::GetStyle() returns a copy, not a live reference. Mutate the returned Style object, then call Cell::SetStyle() explicitly to apply it.

Frequently Asked Questions

Does PutValue() accept any PHP type?

It accepts the typed values confirmed in the API surface (strings, numbers, booleans). See the API reference for the exact set supported by Cell.

Is TryRepairPackage required for every load?

No — only for files of unknown quality. A file your own code just saved does not need repair options.

See Also