Giter Site home page Giter Site logo

avadim483 / fast-excel-writer Goto Github PK

View Code? Open in Web Editor NEW
130.0 6.0 25.0 1.65 MB

Lightweight and very fast XLSX Excel Spreadsheet Writer in PHP

License: MIT License

PHP 99.98% VBScript 0.02%
excel excelwriter php php-library phpexcel spreadsheets parser

fast-excel-writer's Introduction

Latest Stable Version Total Downloads License PHP Version Require

FastExcelWriter Logo

fastest memory saving multiple worksheet
book and sheet protection multiple charts styling and image insertion

FastExcelWriter

FastExcelWriter is a part of the FastExcelPhp Project which consists of

Introduction

This library is designed to be lightweight, super-fast and requires minimal memory usage.

FastExcelWriter creates Excel compatible spreadsheets in XLSX format (Office 2007+), with many features supported:

  • Takes UTF-8 encoded input
  • Multiple worksheets
  • Supports currency/date/numeric cell formatting, formulas and active hyperlinks
  • Supports most styling options for cells, rows, columns - colors, borders, fonts, etc.
  • You can set the height of the rows and the width of the columns (including auto width calculation)
  • You can add formulas, notes and images in you XLSX-files
  • Supports workbook and sheet protection with/without passwords
  • Supports page settings - page margins, page size
  • Inserting multiple charts

Jump To:

Installation

Use composer to install FastExcelWriter into your project:

composer require avadim/fast-excel-writer

Changes In Version 4

  • Now the library works even faster
  • Added a fluent interface for applying styles.
  • New methods and code refactoring

Changes In Version 5

  • General is Chart support

Usage

You can find usage examples below or in /demo folder

Simple Example

use \avadim\FastExcelWriter\Excel;

$data = [
    ['2003-12-31', 'James', '220'],
    ['2003-8-23', 'Mike', '153.5'],
    ['2003-06-01', 'John', '34.12'],
];

$excel = Excel::create(['Sheet1']);
$sheet = $excel->sheet();

// Write heads
$sheet->writeRow(['Date', 'Name', 'Amount']);

// Write data
foreach($data as $rowData) {
    $rowOptions = [
        'height' => 20,
    ];
    $sheet->writeRow($rowData, $rowOptions);
}

$excel->save('simple.xlsx');

Also, you can download generated file to client (send to browser)

$excel->download('download.xlsx');

Advanced Example

use \avadim\FastExcelWriter\Excel;

$head = ['Date', 'Name', 'Amount'];
$data = [
    ['2003-12-31', 'James', '220'],
    ['2003-8-23', 'Mike', '153.5'],
    ['2003-06-01', 'John', '34.12'],
];
$headStyle = [
    'font' => [
        'style' => 'bold'
    ],
    'text-align' => 'center',
    'vertical-align' => 'center',
    'border' => 'thin',
    'height' => 24,
];

$excel = Excel::create(['Sheet1']);
$sheet = $excel->sheet();

// Write the head row (sets style via array)
$sheet->writeHeader($head, $headStyle);

// The same result with new fluent interface
$sheet->writeHeader($head)
    ->applyFontStyleBold()
    ->applyTextAlign('center', 'center')
    ->applyBorder(Style::BORDER_STYLE_THIN)
    ->applyRowHeight(24);

// Sets columns options - format and width (the first way)
$sheet
    ->setColFormats(['@date', '@text', '0.00'])
    ->setColWidths([12, 14, 5]);

// The seconds way to set columns options
$sheet
    // column and options
    ->setColOptions('A', ['format' => '@date', 'width' => 12])
    // column letter in lower case
    ->setColOptions('b', ['format' => '@text', 'width' => 24])
    // column can be specified by number
    ->setColOptions(3, ['format' => '0.00', 'width' => 15, 'color' => '#090'])
;

// The third way - all options in multilevel array (first level keys point to columns)
$sheet
    ->setColOptions([
        'A' => ['format' => '@date', 'width' => 12],
        'B' => ['format' => '@text', 'width' => 24],
        'C' => ['format' => '0.00', 'width' => 15, 'color' => '#090'],
    ]);

$rowNum = 1;
foreach($data as $rowData) {
    $rowOptions = [
        'height' => 20,
    ];
    if ($rowNum % 2) {
        $rowOptions['fill-color'] = '#eee';
    }
    $sheet->writeRow($rowData, $rowOptions);
}

$excel->save('simple.xlsx');

Row's settings

You can set row options (styles and height) by the second argument when you use the function writeRow(). Note that in this case these styles will only be applied to those cells in the row where data is written

// Write row data and set height
$rowOptions = [
    'fill-color' => '#fffeee',
    'border' => 'thin',
    'height' => 28,
];
$sheet1->writeRow(['aaa', 'bbb', 'ccc'], $rowOptions);

Other way with the same result

$sheet1->writeRow(['aaa', 'bbb', 'ccc', null, 'eee'])
    ->applyFillColor('#fffeee')
    ->applyBorder('thin')
    ->applyRowHeight(28);

You can set row's height or visibility

// Set height of row 2 to 33
$sheet1->setRowHeight(2, 33);

// Set height of rows 3,5 and 7 to 33
$sheet1->setRowHeight([3, 5, 7], 33);

// Set heights of several rows
$sheet1->setRowHeights([1 => 20, 2 => 33, 3 => 40]);

// Hide row 8
$sheet1->setRowVisible(8, false);

// Other way
$sheet1->setRowHidden(8);

// Hide rows 9, 10, 11
$sheet1->setRowVisible([9, 10, 11], false);

// Show row 10
$sheet1->setRowVisible(10, true);

IMPORTANT: You can only use the setRowXX() functions on rows numbered at least as high as the current one. See Writing Row by Row vs Direct Therefore, the following code will throw an error "Row number must be greater then written rows"

$sheet = $excel->sheet();
// Write row 1
$sheet->writeRow(['aaa1', 'bbb1', 'ccc1']);
// Write row 2
$sheet->writeRow(['aaa2', 'bbb2', 'ccc2']);
// Try to set height of previous row 1
$sheet->setRowHeight(1, 33);

Column's settings

Column widths can be set in several ways

// Set width of column D to 24
$this->setColWidth('D', 24);
$this->setColOptions('D', ['width' => 24]);
// Set auto width
$this->setColWidth('D', 'auto');
$this->setColWidthAuto('D');
$this->setColOptions('D', ['width' => 'auto']);

// Set width of specific columns
$sheet1->setColWidths(['B' => 10, 'C' => 'auto', 'E' => 30, 'F' => 40]);
// Set width of columns from 'A'
$sheet1->setColWidths([10, 20, 30, 40], 24);

$colOptions = [
    'B' => ['width' => 10], 
    'C' => ['width' => 'auto'], 
    'E' => ['width' => 30], 
    'F' => ['width' => 40],
];
$sheet1->setColOptions($colOptions);

You can define a minimal width of columns. Note that the minimum value has higher priority

// Set minimum width to 20 
$this->setColMinWidth('D', 20);
// The value 10 will not be set because it is less than the minimum value
$this->setColWidth('D', 10);
// But width 30 will be set
$this->setColWidth('D', 30);
// The column width will be set to the width of the content, but not less than 20
$this->setColWidthAuto('D');

Define Named Ranges

FastExcelWriter supports named ranges and does not support named formulae. A named ranges provides a name reference to a cell or a range of cells. All named ranges are added to the workbook so all names must be unique, but you can define named ranges in a sheet or in a workbook.

Also range names must start with a letter or underscore, have no spaces, and be no longer than 255 characters.

$excel = Excel::create();
$excel->setFileName($outFileName);
$sheet = $excel->sheet();

// Named a single cell
$sheet->addNamedRange('B2', 'cell_name');

// Named range in a sheet
$sheet->addNamedRange('c2:e3', 'range_name');

// Add named range in a workbook (sheet name required)
$excel->addNamedRange('Sheet1!A1:F5', 'A1_F5');

// You can define name using applyNamedRange()
$sheet->writeCell(1000)->applyNamedRange('Value');
$sheet->writeCell(0.12)->applyNamedRange('Rate');
// Add the formula using names
$sheet->writeCell('=Value*Rate');

Adding Notes

There are currently two types of comments in Excel - comments and notes (see The difference between threaded comments and notes). Notes are old style comments in Excel (text on a light yellow background). You can add notes to any cells using method addNote()

$sheet1->writeCell('Text to A1');
$sheet1->addNote('A1', 'This is a note for cell A1');

$sheet1->writeCell('Text to B1')->addNote('This is a note for B1');
$sheet1->writeTo('C4', 'Text to C4')->addNote('Note for C1');

// If you specify a range of cells, then the note will be added to the left top cell
$sheet1->addNote('E4:F8', "This note\nwill added to E4");

// You can split text into multiple lines
$sheet1->addNote('D7', "Line 1\nLine 2");

You can change some note options. Allowed options of a note are:

  • width - default value is '96pt'
  • height - default value is '55.5pt'
  • fill_color - default value is '#FFFFE1'
  • show - default value is false
$sheet1->addNote('A1', 'This is a note for cell A1', ['width' => '200pt', 'height' => '100pt', 'fill_color' => '#ffcccc']);

// Parameters "width" and "height" can be numeric, by default these values are in points
// The "fill_color" parameter can be shortened
$noteStyle = [
    'width' => 200, // equivalent to '200pt'
    'height' => 100, // equivalent to '100pt'
    'fill_color' => 'fcc', // equivalent to '#ffcccc'
];
$sheet1->writeCell('Text to B1')->addNote('This is a note for B1', $noteStyle);

// This note is visible when the Excel workbook is displayed
$sheet1->addNote('C8', 'This note is always visible', ['show' => true]);

Adding Images

// Insert an image to the cell A1
$sheet1->addImage('A1', 'path/to/file');

// Insert an image to the cell B2 and set with to 150 pixels (height will change proportionally)
$sheet1->addImage('B2', 'path/to/file', ['width' => 150]);

// Set height to 150 pixels (with will change proportionally)
$sheet1->addImage('C3', 'path/to/file', ['height' => 150]);

// Set size in pixels
$sheet1->addImage('D4', 'path/to/file', ['width' => 150, 'height' => 150]);

FastExcelWriter vs PhpSpreadsheet

PhpSpreadsheet is a perfect library with wonderful features for reading and writing many document formats. FastExcelWriter can only write and only in XLSX format, but does it very fast and with minimal memory usage.

FastExcelWriter:

  • 7-9 times faster
  • uses less memory by 8-10 times
  • supports writing huge 100K+ row spreadsheets

Benchmark of PhpSpreadsheet (P) and FastExcelWriter (F), spreadsheet generation without styles

Rows x Cols Time P Time F Memory P Memory F
1000 x 5 0.98 sec 0.19 sec 2,048 Kb 2,048 Kb
1000 x 25 4.68 sec 1.36 sec 14,336 Kb 2,048 Kb
5000 x 25 23.19 sec 3.61 sec 77,824 Kb 2,048 Kb
10000 x 50 105.8 sec 13.02 sec 256,000 Kb 2,048 Kb

Do you want to support FastExcelWriter?

if you find this package useful you can support and donate to me for a cup of coffee:

  • USDT (TRC20) TSsUFvJehQBJCKeYgNNR1cpswY6JZnbZK7
  • USDT (ERC20) 0x5244519D65035aF868a010C2f68a086F473FC82b
  • ETH 0x5244519D65035aF868a010C2f68a086F473FC82b

Or just give me a star on GitHub :)

fast-excel-writer's People

Contributors

albertbrufau avatar avadim483 avatar jarrod-colluco avatar johnchung2002 avatar xdrew avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

fast-excel-writer's Issues

Set Default Font is used only for written cells

This is an example:

$excel = Excel::create(
    [
        'test',
    ],
)
    ->setDefaultStyle([Style::FONT => [Style::FONT_NAME => 'Calibri', Style::FONT_SIZE => 11]]);

$sheet = $excel->sheet(1);

$sheet->writeCell('TEST');

The Excel file has the right font only in cell A1, in the rest of the file Arial 10 is used.

If this is intended to guarantee high performance, I still think it is better to change the font from Arial 10 to Calibri 11 which seems to be the current Excel standard.

Thanks

height style not working in header

I have:

$headStyle = [
	'font' => ['style' => 'bold'],
	'text-align' => 'center',
	'vertical-align' => 'center',
	'text-wrap' => true,
	'height' => 36,
];

$sheet->writeHeader($fld, $headStyle);

all work except height.
also sheet->setRowHeight(1, 36); in header not work

also sheet->setRowHeight(1, 36); in header work only if $sheet->writeHeader($fld);

how to do?

strftime deprecated in PHP 8.1

The Excel class is using the strftime method in lines 167/168 to determine the local date format.
But this method is deprecated in PHP 8.1 and should be replaced.

Remove temporary file

Hi,

Your lib seems very fast, good job!

However, please add unlink($tmpFile); at the end of the method Excel::download().

Thanks!

How to write a formula

I have a model that have a formula '=PROCV(E4;'EFETIVO ATUALIZADO'!$B:$D;2;FALSO)'
In the library I was using this way $fomulaTest = "=PROCV(RC[-1];'EFETIVO ATUALIZADO'!$B:$D;2;FALSO)";

And don't work, how to write a formula in this case?

Fatal error: Uncaught Error: Class "Locale" not found

Fatal error: Uncaught Error: Class "Locale" not found in /Applications/XAMPP/xamppfiles/htdocs/project_name/vendor/avadim/fast-excel-writer/src/FastExcelWriter/Excel.php:295

After some fiddling around, I managed to make it work (temp directory was a pain to configure as well, the error message is always using "sys_get_temp_dir()" even when tempDir is overwrite. But nonetheless, it work after. The last error was the above, I managed to make it work by commenting out the lines to set Locale, but is it the intended result or is a file missing?

Thanks

Screenshot 2024-03-25 at 3 59 48 PM

Save File when cell value has formula

Hi I try to export a formula sheet and upload to googlesheets.
but formula cell not works correctly. It just show formula string, not formula execute result.

so I unziped xlsx, found sheet.xml. the formula cell value like this:
<c r="C4" s="0"><f>=SUM(C1:C3)</f></c>

and I try to check other xlsx file download from googlesheets
<c r="B4" s="2"><f t="shared" ref="B4:C4" si="2">SUM(B1:B3)</f><v>2004</v></c>
I found the formula cell value not contain '=' on first char

I modified Writer.php Line 996 to remove '='
$file->write('' . mb_substr(self::xmlSpecialChars($value), 1) . '');
and It works fine

thank you

Feature request

I understand that the main purpose of the library is speed (and it is awesome at that!). I have not seen these implemented, but would be useful if speed is not compromised, of course:

  1. Set a sheet's zoom level
  2. Protect/Uprotect cells/sheets

Thanks!

New Features

Please correct me if I'm wrong, but I can't see that comments or conditional styles are built into this library. Is there any plans in place to do so?

applyRowHeight doesnt seem to work if row contains just an image?

$sFilename='sample-image.png';
$sCell='A1';
$this->oWriterSheet->addImage($sCell, $sFilename);
// set row height to that of image
$aImages=$this->oWriterSheet->getImages();
$aImages=end($a);
$this->oWriterSheet->applyRowHeight($aImages['height'])->nextRow();

$this->oWriterSheet->writeHeader(['COL1','COL2','COL3')->applyFontStyleBold()->applyBgColor('#E0E0E0');

Without the ->nextRow(), the graphic AND the header row take up row #0.
I have also tried $this->oWriterSheet->setRowHeight(1, $aImages['height']) instead of the applyRowHeight() but it still doesn't change the height.

The above example without the call to nextRow() will include the graphic but it will overhang the COL1, COL2 and COL3 row as the first row is also the same height as the second one.

Am I doing something wrong?

Missing return

Sometimes when I create an XLS in PHP with Avadim Fast-Excel-Writer the Ajax request remains waiting without data.
What can it depend on?
How can I investigate it?

T_ENCAPSED_AND_WHITESPACE

I get in a server with Php 7.4
Parse error: syntax error, unexpected ''/^\w+$/u' (T_ENCAPSED_AND_WHITESPACE) in vendor/avadim/fast-excel-writer/src/FastExcelWriter/Sheet.php on line 2916

if (!preg_match('/^\w+$/u', $name)) {

Not problem in other server with PHP 8.3.2

Why?

Chart on differnt sheets

Hello,
thanks for good work.
But I'm fighting with charts on different sheets. Mybe an error

Can you help?

Thanks Michael

Why is list of available fonts so limited?

I would like to use the Calibri font but doing the following causes excel to complain about worksheet errors:

$sheet->writeHeader($headings, [
    Style::FONT => [
        Style::FONT_NAME => 'Calibri',
        Style::FONT_SIZE => 10,
        Style::FONT_STYLE => Style::FONT_STYLE_BOLD,
    ]
]);

I see theres a function Style::_getFamilyFont() which has $defaultFontsNames. If I add Calibri to this array then things work, but I cant see any way to add to this array from my application code:

$defaultFontsNames = [
    'Times New Roman' => [
        'name' => 'Times New Roman',
        'family' => 1,
    ],
    'Arial' => [
        'name' => 'Arial',
        'family' => 2,
    ],
    'Courier New' => [
        'name' => 'Courier New',
        'family' => 3,
    ],
    'Comic Sans MS' => [
        'name' => 'Comic Sans MS',
        'family' => 4,
    ],

    +++++
    'Calibri' => [
        'name' => 'Calibri',
        'family' => 5,
    ],
];

2 questions:

  • Whats the reason for this list of 4 specific fonts only? And of all fonts why comic sans as one of these 4? 😆
  • Can we have a way to set the default available fonts - or rather can we just use any font we like in the style array?

FYI just found this library and am currently trying to port some exports over from the now archived box\spout library,

Memory usage for 100K Rows is >1.5GB

Hi,

I have been trying to write an .xlsx file from a really large dataset of 350K rows & 150 Columns. How would you approach writing such a large file. Pl find the below dry run results and the code.

For 10K Records
elapsed time: 10.374 sec
Memory peak usage: 76 MB

For 50K Records
Elapsed time: 56.563 sec
Memory peak usage: 364 MB

For 75K Records
Elapsed time: 97.748 sec
Memory peak usage: 546 MB

<?php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/src/autoload.php';

use \avadim\FastExcelWriter\Excel;

function generateXlsx($savePath, $filename, $jsonFilePath) {
    if ($jsonFilePath === null) { die("Error: File path is null."); }

    $jsonData = file_get_contents($jsonFilePath);
    $data = json_decode($jsonData, true);
    if ($data === null) { die("Error: Failed to decode JSON from text file."); }

    $header = [
        'c1-text'   => '@', //text
        'c2-text'   => '@text', //text
        'c3-integer' => '@integer',
        'c4-integer' => ['text-color' => '#f0f'], // default format
        'c5-money'  => '@money',
        'c6-price'  => '#\'##0.000', //custom numeric format
        'c7-date'   => ['format' => '@date', 'width' => 'auto'],
        'c8-date'   => ['format' => 'YYYY-MM-DD', 'width' => 11],
        'c9-time'   => 'H:MM',
    ];

    $outFileName = $savePath . '/' . $filename;

    $timer = microtime(true);

    $excel = Excel::create();
    $sheet = $excel->getSheet();

    $rowOptions = ['font-style' => 'bold'];
    $sheet->writeHeader($header, $rowOptions);

    foreach($data as $row) { $sheet->writeRow($row); }

    $excel->save($outFileName);

    echo '<b>', basename(__FILE__, '.php'), "</b><br>\n<br>\n";
    echo 'out filename: ', $outFileName, "<br>\n";
    echo 'elapsed time: ', round(microtime(true) - $timer, 3), ' sec', "<br>\n";
    echo 'Memory peak usage: ', memory_get_peak_usage(true) / (1024 * 1024), ' MB<br>';
}

// Check if the script is invoked with the required parameters
if(isset($argv) && count($argv) >= 4) {
    $savePath = $argv[1];
    $filename = $argv[2];
    $jsonFilePath = $argv[3];

    // Generate the XLSX file
    generateXlsx($savePath, $filename, $jsonFilePath);
} else {
    echo "Usage: php script.php <savePath> <filename> <json_encoded_rows>\n";
}
?>

`
image

Cannot use ColWidth with any forms

Using setColWidth, or other forms for setting width, results in "sorry, your excel document is corrupted...", and the reparation proposed removes the width setting (repaired Part: part /xl/worksheets/sheet1.xml with XML error. Loading error. Line 2, column 0..
Ex : your demo file : demo-v4-03-widths-heights.php
Office version tested : office 365 and Office 2016

error on php 8.1

hi
on php 8.1 we have error

Fatal error: Cannot make static method XMLReader::open() non static in class avadim\FastExcelReader\Reader in
vendor\avadim\fast-excel-reader\src\FastExcelReader\Reader.php on line 32

Bugfix: Linux not identifying .xlsx as correct mimetype...

In order to differentiate from regular .zip files, the mimetype looks for files added to the .xlsx in order (as per Office 2007+), in particular:
[Content_Types].xml needs to be first followed by at least one file in the xl/ folder...

reference:
https://stackoverflow.com/questions/7274030/detect-excel-xlsx-file-mimetype-via-php

Can you tweak the saveToFile function?

PS. It may be more prudent to move the exception for "No worksheets defined" BEFORE the file_exists/unlink check as no worksheets will result in the file being deleted without creating any output!
<Maybe even just before the $zip->close() in case any other problems/exceptions cause the .zip not to be created?>

4.81 not work

4.81 not work I have to switch to previous.


Fatal error: Uncaught Error: Class "avadim\FastExcelHelper\Helper" not found in c:\test\FastExcelWriter\FastExcelWriter\Excel.php:586 Stack trace: #0 c:\test\FastExcelWriter\FastExcelWriter\Excel.php(824): avadim\FastExcelWriter\Excel::colNumber('A') #1 c:\test\FastExcelWriter\FastExcelWriter\Excel.php(925): avadim\FastExcelWriter\Excel::rangeDimensionRelative('A1', NULL, true) #2 c:\test\FastExcelWriter\FastExcelWriter\Sheet.php(2231): avadim\FastExcelWriter\Excel::rangeDimension('A1', true) #3 c:\test\FastExcelWriter\FastExcelWriter\Sheet.php(2199): avadim\FastExcelWriter\Sheet->_rangeDimension('A1') #4 c:\test\FastExcelWriter\FastExcelWriter\Sheet.php(2266): avadim\FastExcelWriter\Sheet->_parseAddress('A1') #5 c:\test\FastExcelWriter\FastExcelWriter\Sheet.php(199): avadim\FastExcelWriter\Sheet->_setCellData('A1', NULL, NULL, false) #6 c:\test\FastExcelWriter\FastExcelWriter\Excel.php(247): avadim\FastExcelWriter\Sheet->__construct('Alfa') #7 c:\test\FastExcelWriter\FastExcelWriter\Excel.php(1054): avadim\FastExcelWriter\Excel::createSheet('Alfa') #8 c:\test\FastExcelWriter\FastExcelWriter\Excel.php(226): avadim\FastExcelWriter\Excel->makeSheet('Alfa') #9 c:\test\calc.php(749): avadim\FastExcelWriter\Excel::create(Array)

Autoloader not using correct directory separators

Hi,
When using the autoloader it does not correctly create a path to the php file.

Line 6:
include __DIR__ . '/FastExcelWriter/' . str_replace($namespace, '/', $class) . '.php';

The '\\' (or '\' if you will) in the $class is not converted to a '/' and results in an error on my linux machine, (notice the last directory seperator):
PHP Warning: include(...path.../FastExcelWriter//Exception\\SaveException.php): failed to open stream: No such file or directory in ...path.../autoload.php on line 6

I've fixed this by adding another replace which converts the '\' into '/' and then it works fine.

The issue seems also present in the fast-excel-reader.

Inconsistency on formatCode per numFmtId

Hi,
Some of the format patterns for 14 - 22 appear to be locale/short date/long date combinations as my Excel show these values:

14=>dd/mm/yyyy  (my windows short date format)
15=>dd-mmm-yy
16=>dd-mmm
17=>mmm-yy
18=>h:mm
19=>h:mm AM/PM
20=>h:mm:ss AM/PM
21=>hh:mm
22=>hh:mm:ss

Auto size column

Hi.
Trying to switch from PhpSpreadsheet to your solution and have a few questions:

  1. PhpSpreadsheet has a setAutoSize() function which sets the automatic column size by content. Do you have something similar? Or do you have to manually set the width and height for each column?
  2. Is there some way to make a URL link to the cell?

Note dimensions

Hi @aVadim483

Thanks for your great work on adding notes in. I have noticed that when adding a note, it needs to be escaped correctly, otherwise certain characters may break the spreadsheet.

I wanted to know whether it was possible to define the width/height of the note? I have seen in the addNote() function that you set it through the array - is it possible to expose this to the function or at least allow us to override the note array so that we can specify those ourselves?

The notes don't support text-wrapping so when adding a few lines of text, we need to make sure the note width/height is long enough to read.

Time format as 00:00:00

Полагаю, что метод convertDateTime не корректно обрабатывает время, если на входе 00:00:00
В итоге помечает как тип n_auto

redirecting the output to client user

I am trying to add to the header these

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment;filename={/var/www/dumyah/tmp/$file_name}");
header("Cache-Control: max-age=0");

so that I can call the output that was saved as excel to the user's device, but it's not working, any help would be appreciated

phpspreadsheet has the same writing speed

I just tested with your library and phpspreadsheet to compare the speed of the writing of the excel
with the 40k+ lines of row and 50 column of data.

Both takes about 23min, so i don't see any improvement for the library?
Unless I'm doing it wrongly.
Kindly provide any extra advice that I should know about.
Thanks

        $excel = Excel::create(['Sheet1'], $temp_dir_array);
        $sheet = $excel->sheet();

        $sheet->setTopLeftCell('B2'); //start from B2

        //write the header, report name, gen date
        if (!empty($excel_data_array['report_header'])) {
            $report_header = $excel_data_array['report_header'];
            $merging_row_cell_count = 2; //header start on 2nd row
            foreach ($report_header as $row) {
                $sheet->writeRow($row)->mergeCells("B$merging_row_cell_count:E$merging_row_cell_count");
                //merge 3 column cells together
                $merging_row_cell_count++;
            }

            $sheet->skipRow(); // Skip a row
        }

        $headStyle = [
            'font' => [
                'style' => 'bold',
            ],
        ];

        //write the table header
        $table_header = $excel_data_array['table_header'];
        $sheet->writeRow($table_header, $headStyle)->applyBorder('thin')->applyTextAlign('center');

        // Assuming $table_header is an array containing headers up to max column
        // Set column width for columns C to the end column
        $end_column = count($table_header) + 2; // Add 2 to skip columns A and B
        for ($col = 3; $col <= $end_column; $col++) {
            $sheet->setColWidthAuto($col);
        }

        //write all td
        $table_data = $excel_data_array['table_data'];
        foreach($table_data as $row_data) {
            $sheet->writeRow($row_data)->applyBorder('thin')->applyTextAlign('center');
        }

Deprecated functions in PHP 8.1 still in use

Hello,

There are some deprecated functions in PHP 8.1 still in use:

ctype_digit() => Argument of type float will be interpreted as string in the future in src/FastExcelWriter/Writer.php on line 1116
strftime() => src/FastExcelWriter/Excel.php on line 168

Regards,

Wrong range Y1

Hi!

    public static function colIndex($colLetter)
    {
        // Strip cell reference down to just letters
        $letters = preg_replace('/[^A-Z]/', '', $colLetter);

        if ($letters > 'XFD') {
            return -1;
        }
        // Iterate through each letter, starting at the back to increment the value
        for ($index = 0, $i = 0; $letters !== ''; $letters = substr($letters, 0, -1), $i++) {
            $index += (ord(substr($letters, -1)) - 64) * (26 ** $i);
        }

        return ($index <= self::EXCEL_2007_MAX_COL) ? (int)$index: -1;
    }

The $letters > 'XFD' check fails when you pass Y or Z or XX.

To reploduce, you could try:

$spreadsheet = Excel::create();
$sheet = $spreadsheet->getSheet('test');
$sheet->setValue('Y1', 'smth');

Btw, what does that check do? )

Sum of Times

Hello,
The sum of times is wrong because the correct format should be [h]:mm
How can I manage this format with your library?

set Date format in Locale Settings

I have to get the date format as:
DD/MM/YYYY
It work in Windows server but not in Linux server where it become:
YYYY/MM/DD
I tryed to force with

$excel->style->setLocaleSettings([
      'formats' => [
          '@DATE' => 'DD-MM-YYYY',
          '@TIME' => 'HH:MM:SS',
          '@DATETIME' => 'DD-MM-YYYY HH:MM:SS',
          '@MONEY' => '# ##0,00',
      ],
  ]
);

And it works.
Do it is the right via?

How to insert image

How to insert image in fast-excel-writer because i didn't see it in the documentation?

How to set Hyperlink using writeRow

When i try to add options to an array to set a hyperlink for a cell, it shows only an empty cell:

This is how i´m trying to do:

$array_cells = array();
$array_cells[] = $name;
$array_cells[] = $company;
$array_cells[] = $otheroptions;
...
$Link = [$value, ['hyperlink' => true]];
$array_cells[] = $Link;
$sheet->writeRow($array_cells, $rowOptions, $cellsStyle);

What is the correct way to set an hyperlink using writeRow option?

Thanks for your great work!

Excel unreadable contact

Hello,

I was using version 2.3 after updating to 4.2 when generating the Excel file and opening it using Microsoft Excel I got the below alert
but nothing changes in style and contact, But when open the file using LibreOffice I did not face an alert
Microsoft Excel Version 2307 Build 16.0.16626.20110
image

Do I do something wrong below is part of the code for one sheet

                $rowStyle = ['text-align' => 'center', 'border' => 'thin'];
                $excel = Excel::create(['DW', 'In Deal', 'Out OutBy', 'Country', 'Symbols']);
                // DW Deals Sheet ---------------------------------------------------------
                $sheet = $excel->getSheet('DW');
                $sheet->setColWidth(['A', 'B', 'C', 'D', 'G', 'H', 'I'], 'auto');
                $sheet->setFreeze(1);
                $sheet->writeHeader(['Login', 'Amount', 'Time', 'Deal'], $headerStyle);
                $sheet->setColFormat('A', '@integer'); //Login
                $sheet->setColFormat('B', '[BLUE][$$]#,##0.00;[RED]-[$$]#,##0.00'); //Amount
                $sheet->setColFormat('C', 'YYYY-MM-DD HH:MM:SS'); //Time
                $sheet->setColFormat('D', '@integer'); //Deal

              (some query logic)

                $areaTotal = $sheet->makeArea('G4:I7');
                $areaData = $sheet->beginArea('A2');
                foreach ($query->get() as $key => $row) {

                    $numRow = $key + 2;
                    $areaData->setValue('A' . $numRow, $row->Login, $rowStyle);
                    $areaData->setValue('B' . $numRow, $row->Profit, $rowStyle);
                    $areaData->setValue('C' . $numRow, $row->Time, $rowStyle);
                    $areaData->setValue('D' . $numRow, $row->Deal, $rowStyle);
              
                }
                //Prepare total section 
                $TotalDeposit = $query->get()->where('Profit', '>', 0)->sum('Profit');
                $TotalWithdrawal = $query->get()->where('Profit', '<', 0)->sum('Profit');
                $countDeposit = $query->get()->where('Profit', '>', 0)->count();
                $countWithdrawal = $query->get()->where('Profit', '<', 0)->count();


                $areaTotal->setValue('I4', 'Total Rows', $rowStyle)->applyFontStyleBold();
                $areaTotal->setValue('G5', 'Total Deposit', $rowStyle)->applyFontColor('#3A00FF')->applyFontStyleBold();
                $areaTotal->setValue('G6', 'Total Withdrawal', $rowStyle)->applyFontColor('#FF0000')->applyFontStyleBold();
                $areaTotal->setValue('G7', 'Net', $rowStyle)->applyFontStyleBold();

                $TotalStyle = ['format' => '[BLUE][$$]#,##0.00;[RED]-[$$]#,##0.00', 'text-align' => 'center', 'border' => 'thin', 'font' => ['style' => 'bold']];
                $areaTotal->setValue('H5', $TotalDeposit, $TotalStyle);
                $areaTotal->setValue('H6', $TotalWithdrawal, $TotalStyle);
                $areaTotal->setValue('H7', $TotalDeposit + $TotalWithdrawal, ['format' => '[$$]#,##0.00', 'text-align' => 'center', 'border' => 'thin', 'font' => ['style' => 'bold']]);
                $areaTotal->setValue('I5', $countDeposit, $rowStyle)->applyFontStyleBold();
                $areaTotal->setValue('I6', $countWithdrawal, $rowStyle)->applyFontStyleBold();
                $areaTotal->setValue('I7', $countDeposit + $countWithdrawal, ['format' => '#,##0', 'text-align' => 'center', 'border' => 'thin', 'font' => ['style' => 'bold']]);
//save file

Fill color in MS Office365

I had a problem with fill color after creating Excel file - when file is opened in Google Spreadsheet everything is OK (header is red). But opening in MS Office 365 gives kind of greyish dots (enclosing screenshot).
issue

Style code looks like this:
$headStyle = [
'font' => ['style' => 'bold'],
'fill' => '#f00',
'text-align' => 'center',
'vertical-align' => 'center',
'border' => 'thin',
];

QUESTION: Append to existing file

How would you go about opening existing XLSX and appending data to it? Is there some sort of option when calling Excel::create() to actually open an existing file rather than starting a fresh one?

In a nutshell, I have a job that writes few lines into XLSX file and what I would like to do is to save that file and later come back to it on a different job and append more rows to the very same file. Is there a functionality to write to an existing file?

Little issue

Work fine and fast ;o)

Good job.

One remarks : when writing 'hello world ' the produced file contains 'hello world'.

Meaning that the last space character is removed.

Can it be solved ?

Row number must be greater than written rows

Hello Everyone,

I facing the issue after using writeRow to fill A B C and D columns I want to write the total in the empty area F3:H6
so I use makeArea to select the area I want work with but I got error row number must be greater than written rows
Is there any way to overwrite these rows without changing the row data?

image

Output Error

I have this error that appears after the sheet is generated, how can i go about it?
I am using version 4.11.0
Screenshot from 2024-02-12 20-50-22

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.