Git Product home page Git Product logo

php_xlsxwriter's Introduction

PHP_XLSXWriter

This library is designed to be lightweight, and have minimal memory usage.

It is designed to output an Excel compatible spreadsheet in (Office 2007+) xlsx format, with just basic features supported:

  • supports PHP 5.2.1+
  • takes UTF-8 encoded input
  • multiple worksheets
  • supports currency/date/numeric cell formatting, simple formulas
  • supports basic cell styling
  • supports writing huge 100K+ row spreadsheets

Never run out of memory with PHPExcel again.

Simple PHP CLI example:

$data = array(
    array('year','month','amount'),
    array('2003','1','220'),
    array('2003','2','153.5'),
);

$writer = new XLSXWriter();
$writer->writeSheet($data);
$writer->writeToFile('output.xlsx');

Simple/Advanced Cell Formats:

$header = array(
  'created'=>'date',
  'product_id'=>'integer',
  'quantity'=>'#,##0',
  'amount'=>'price',
  'description'=>'string',
  'tax'=>'[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00',
);
$data = array(
    array('2015-01-01',873,1,'44.00','misc','=D2*0.05'),
    array('2015-01-12',324,2,'88.00','none','=D3*0.05'),
);

$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', $header );
foreach($data as $row)
	$writer->writeSheetRow('Sheet1', $row );
$writer->writeToFile('example.xlsx');

50000 rows: (1.4s, 0MB memory usage)

include_once("xlsxwriter.class.php");
$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', array('c1'=>'integer','c2'=>'integer','c3'=>'integer','c4'=>'integer') );
for($i=0; $i<50000; $i++)
{
    $writer->writeSheetRow('Sheet1', array($i, $i+1, $i+2, $i+3) );
}
$writer->writeToFile('huge.xlsx');
echo '#'.floor((memory_get_peak_usage())/1024/1024)."MB"."\n";
rows time memory
50000 1.4s 0MB
100000 2.7s 0MB
150000 4.1s 0MB
200000 5.7s 0MB
250000 7.0s 0MB

Simple cell formats map to more advanced cell formats

simple formats format code
string @
integer 0
date YYYY-MM-DD
datetime YYYY-MM-DD HH:MM:SS
time HH:MM:SS
price #,##0.00
dollar [$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00
euro #,##0.00 [$€-407];[RED]-#,##0.00 [$€-407]

Basic cell styles have been available since version 0.30

style allowed values
font Arial, Times New Roman, Courier New, Comic Sans MS
font-size 8,9,10,11,12 ...
font-style bold, italic, underline, strikethrough or multiple ie: 'bold,italic'
border left, right, top, bottom, or multiple ie: 'top,left'
border-style thin, medium, thick, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot
border-color #RRGGBB, ie: #ff99cc or #f9c
color #RRGGBB, ie: #ff99cc or #f9c
fill #RRGGBB, ie: #eeffee or #efe
halign general, left, right, justify, center
valign bottom, center, distributed

php_xlsxwriter's People

Contributors

andrewkesper avatar c-schmitz avatar eom avatar farhantahir avatar fliespl avatar fugi avatar fulgurio avatar goktugozturk avatar heew avatar ivanbarlog avatar jpastoor avatar kkr-christopher avatar ldav avatar lewa avatar lieszkol avatar lourdas avatar malvineous avatar marktinsley avatar mk-j avatar radstake avatar sebastiankalwa avatar shinychang avatar stephane-rouleau avatar stof avatar unamatasanatarai avatar xrobau 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  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

php_xlsxwriter's Issues

Cell format documentation

Is there anywhere where the cell formats are documented? Looking at the code I can see a few types listed, but nothing for things like number-as-text to preserve leading zeroes. I also can't see how to specify percentages either.

I've downloaded the ECMA-376 specs but can't see anything in there that lists these formats either - I'm sure they're there I just don't know what to search for.

Would it be possible to include a reference list of available format specifiers somewhere, either in the code or on the project's GitHub wiki page?

writeToFile(php://output) producing blank document

Switching from PHPExcel to PHP_XLSXWriter because I don't need fancy formatting and it was slow and memory intensive. Found the following issue:

The first writeToFile instruction produces the expected result, a file in the server's file system.
The second writeToFile downloads a file straight to the computer, but that file is empty when opened in Excel.
Same result if it's one or the other on it's own.
Without the headers one would expect the browser to just display the raw file, but it's blank.

$writer->writeToFile(str_replace('.php', '.xlsx', __FILE__));
header('Set-Cookie: fileDownload=true; path=/');
header('Cache-Control: max-age=60, must-revalidate');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$file_name.'.xls"');
$writer->writeToFile('php://output');

Any ideas what's going on?

Return stream.

Currently the only way to get the binary data are the "writeTo" functions.

  • writeToFile
  • writeToStdOut
  • writeToString

With PSR-7 more people will instead be using Streams to model Response in their application.
It would be great if there was a getStream function, that would open a handle to the temporary file with the given parameters.

   public function getStream($mode = 'r') {
           return fopen($this->tempFilename(), $mode, false);
   }

I can implement it and make a pull request if you prefer.

Writing a string with numbers

If you try to write a string with padded 0's ("00001", "00002") - the class will assume you're writing a number and end up with "1", "2"

I modified this line to fix:
-if (is_numeric($value)
+if ((is_numeric($value)) && ($cell_format!='string'))

Formula's?

I don't see any examples of using formulas? I don't see it in the source code either. Any help on this?

File creation / string building

This isn't really an issue, more of a question or idea. I'm writing about 8000 rows, and 8 columns to a spreadsheet. It takes about 4 seconds, which is quick in comparison to phpexcel. Just wondering if I could speed it up, and had an idea:

Instead of it looping through the data array, and writing to a file for every cell..what if it built a string, and wrote to the file just once, at the end ?

I'm not sure if that would have any performance improvements or not ?

Quick troubleshooting - file not produced...

Hi - following the first example to writeToFile('output.xlsx') but can't find the file. Searched everywhere. Script is getting to that point and beyond. Anything I should look at permissions-wise or ???

Where should I expect to see the file saved?
Thanks in advance!

WriteToStdOut on Google App Engine

How can I use this on Google App Engine to download generated files the way WriteToStdOut works on "normal" hosts? I'm using the example.php file with the headers - it triggers a download of example.xlsx, but that download is always zero bytes.

Long number is rounded

I had long number 3273222508910005, but it'll be written:

3.27322250891E+015

and displayed as: 3273222508910000

Format Codes

thx for the great class.
I've skimed trought the code. but wasnt able to edit it.
could you add formating for numbers just as text? if I add a value with 2 decimals like 13.40
it converts to 13,4 - but i want it to stay unformated

Error / No Output

I'm sure I am missing something obvious, but I cannot get the writeToStdOut and writeToFile functions to work as shown in the examples. When I use writeToFile, I am getting an empty file. When I use writeToStdOut I am getting this error: Warning: readfile(C:\Windows\Temp\xlsAF22.tmp): failed to open stream: No such file or directory in xlsxwriter.class.php on line 40. What am I missing?

Enable Cell Protect (Lock)

Hi, I need to lock some particular cells from file. I can't find any references. Please help me to resolve this.

matrix input

Hello,

how can I add a matrix formula? This formula is added with CTRL+SHIFT+RETURN in the UI, eg {=FREQUENCY(...)}, but if I add the {} to the PHP array this does not work.

Thx

Adding Data to a sheet

When it comes to big queries I am selecting them in chunks (limit,offset) and then write those chunks into the spreadsheet. This works well with PHPEXcel. Are you planning on integrating this into your class ?

multi-line cells support?

Hi there,

I am not sure if your lib supports it from the different examples I read so I am asking now : is it possible to to multi-line cells with your write ? if yes, how ?

i am attaching a screenshot of what I am looking for
screen shot 2015-10-11 at 16 10 46

thx !

Invalid XLSX file if using custom formatting

I found an issue where I'm trying to format using a custom format of "@" and a non-numeric value, but when I do it's creating an invalid XLSX file. Excel is able to repair it, but Libreoffice just replaces all invalid fields with 0. Upon inspection in the code, it looks like @ is getting detected as currency (and therefore numeric rather than a string) on line 161 due to an incorrect regex, causing the writer to insert the value directly rather than using a shared string.

I don't know how to perform a pull request, however I have a diff of the line in question that fixes the issue.

Also: to anyone having issues with Excel complaining about "We found a problem with some content" when using custom formatting, try this change and see if it fixes the issue.

[wms@wmsrdev lib]$ diff xlsxwriter.class.php xlsxwriter.class.php.fixed
161c161
if (preg_match("/$/", $cell_format)) return 'currency';
if (preg_match("/\$/", $cell_format)) return 'currency';

Edit: github auto-format seems to be mangling the diff above, so FYI the top line is the original line, and the bottom line is the fixed line.

column count

Hi,

I'm not so sure what's the best way to report this, but i had problems generating an excel sheet from a database automatically (column count can vary).
I've ended up changing the below and now it works fine.

public function writeSheetRow($sheet_name, array $row)
    {
        if (empty($sheet_name) || empty($row))
            return;

        self::initializeSheet($sheet_name);
        $sheet = &$this->sheets[$sheet_name];
        if (empty($sheet->cell_formats))
        {
            $sheet->cell_formats = array_fill(0, count($row), 'string');
        }

        $sheet->file_writer->write('<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="' . ($sheet->row_count + 1) . '">');
        $COUNTER = 0; // ADD COUNTER FOR COLUMN
        foreach ($row as $k => $v)
        {
// ORIGINAL : $this->writeCell($sheet->file_writer, $sheet->row_count, $k, $v, $sheet->cell_formats[$k]);
 //CHANGE       
  $this->writeCell($sheet->file_writer, $sheet->row_count, $COUNTER, $v, $sheet->cell_formats[$COUNTER]);
            $COUNTER++;


        }

Datetime celltype not show correctly in iphone.

When I use datetime as the celltype, and the data like Carbon::now();
And it could be shown right in Excel 2016 (Windows version), but not in iPhone, Android and HTML5 reader. The date will be displayed like " 2016-02-58 15:45", the day is wrong absolutely.
Hope you can fix it. Thank you.

Issue: numeric strings (zip codes and phone numbers) not handled well

Hello again,

Here's a new issue I uncovered today in testing for a client. Phone numbers and zip codes often have their leading zeros removed or display as a number (1.23E+15). I added the middle to lines of code following line 234 (I am including the line before and after to the 2 lines I added):

        $file->write('<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.($value*1).'</v></c>');//int,float, etc
    } elseif ($cell_format=='string'){
        $file->write('<c r="'.$cell.'" s="'.$s.'" t="s"><v>'.self::xmlspecialchars($this->setSharedString($value)).'</v></c>');//string
    } elseif ($value{0}!='0' && ctype_digit($value)){ //excel wants to trim leading zeros

This appears to have the desired affect of having Excel read these as strings irregardless of the cell content.

Thoughts?

Ed

Header styling

Your class is amazingly fast compared to PHPExcel, awesome job! But i would really like to style the headers, is there any possibility to add this feature on the next release? Keep the great job!

tab

You our data has chr(11), your excel while open with error... we need to change chr(11) to chr(13) to won't have any error...

I juste change your code like this :

$this->writeCell($sheet->file_writer, $sheet->row_count, $column_count, $v, $sheet->columns[$column_count]);

to

$this->writeCell($sheet->file_writer, $sheet->row_count, $column_count, str_replace(chr(11), chr(13), $v), $sheet->columns[$column_count]);

Formulas Excel

Hello there! Thanks for the library!

I am trying to write a formula into excel that it isnt excel formula but it is external formula. The output is empty.

The formula is like this "=ASD("SN@CBBT corp";"AVG";" INTERVAL=1m";)"

Generated xlsx won't open in Excel

  1. If a written cell value contains non-ASCII characters you cannot open the xlsx in Excel.
  2. A written cell value such as +542914888847 is written as a numeric value (it passes the filter_var($value, FILTER_VALIDATE_INT) test on line 235) but results in a corrupt xlsx.

I added preg_replace('/[^(\x20-\x7F)]*/', '', $val) in xmlspecialchars() to fix the first problem but I'm not sure the best way to solve the second problem. For now I will treat all values as strings instead.

Write by row and column

Hello everybody!

How can I write by row and column in a specific sheet ? (Excel with multiple sheets)

Is this possible ?

Thanks

The second worksheet is still abnormal.

$data2 = array(
array('2003','01','343.12'),
array('2003','02','345.12'),
);

After my test, all content of the second worksheet is
image
So this means that "array('2003','01','343.12')" is lost.

Warning: fopen() [function.fopen]: Filename cannot be empty

Hi,

I really like your library, since it's simple and very quick!

Last couple of days I've been banging my head regarding an issue I have.
In a WAMP installation on my pc I've created a database and put some data into it. I've created a php script that uses your library to export the contents of the db to an Excel file. On my pc this is working perfectly!
Now I have transferred the database and it's contents to my webhosting provider and uploaded the php script. It now looks exactly the same as my home setup.
Yet, when I fire up the script, I receive a corrupt Excel file. If I rename the extension to html, then it contains following errors:

Warning: fopen() [function.fopen]: Filename cannot be empty in /public/sites/....mysite .../admin/xlsxwriter.class.php on line 540

Warning: str_repeat() [function.str-repeat]: Second argument has to be greater than or equal to 0 in /public/sites/....mysite ../netwerk/admin/xlsxwriter.class.php on line 201

I transferred the same to another test environment and there it's working correct!

I have no clue how to trace this issue further, so I would appreciate it very much if you could help me out here.

Thanks already!

Regards,

Gosse

Invalid content in xml

MS Excel open xlsx files with errors.

<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>
error018240_01.xml
</logFileName>
<summary>
Обнаружены ошибки в файле "G:\unload.xlsx"
</summary>
<removedRecords summary="Список удаленных записей:">
<removedRecord>
Removed records: Formula from part /xl/worksheets/sheet1.xml
</removedRecord>
</removedRecords>
</recoveryLog>

I assume this problem relates with bad chars (http://stackoverflow.com/questions/730133/invalid-characters-in-xml). XLSXWriter::xmlspecialchars contain simple control, I think that this is a serious problem for some cases.

Excel cannot open XLSX file "format for the file extension is not valid"

Hello, I'm having trouble with this library for some weird reason. I've been able to use this without any problem in all my project, except for one of the files: in this one I always get the 'file extension is not valid' when I try to use PHP_XLSXWriter, but I'm using the exact same code as in the other files of my project (in which the library runs perfectly).
Here's the code I'm using to test:

ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

    $filename = "example.xlsx";
    header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    $header = array(
        'year'=>'string',
        'month'=>'string'
    );
    $data1 = array(
        array('2003','1'),
        array('2003','2'),
    );

    $writer = new XLSXWriter();
    $writer->setAuthor('Some Author');
    $writer->writeSheet($data1,'Sheet1',$header);
    $writer->writeToStdOut();
    exit(0);

That's it. But I always get the error message in this specific page. What could be causing this? Any clue??
Thank you so much for your help!

Cell references in lowercase

Hello,
I have problems with cell references because the formula is partially lowercase.

In my PHP code

=COUNTIF(Valeurs.B1:Valeurs.B65000;INDIRECT("A" & ROW()))

In the generated file

=COUNTIF(valeurs.b1:valeurs.b65000;INDIRECT("A" & ROW()))

In the file, I need to change the formula and press enter to get the right formula with capitals letters where they are needed.

Do you have any idea? Thanks for your help.

Error only on Linux

When using class PHP_XLSXWriter on Linux system I always get this error opening the file in Excel:

Parte rimossa: Parte /xl/sharedStrings.xml con errore XML.  (Stringhe)
(Part removed: Part /xl/sharedStrings.xml with error XML. (Strings))
Carattere xml non valido. Riga 2, colonna 1898.
(xml char not valid. Row 2, column 1898.)
Record rimossi: Informazioni cella dalla parte /xl/worksheets/sheet1.xml
(Record removed: cells informations from part /xl/worksheets/sheet1.xml)

On Windows PHP Apache no errors, no problems! I have no idea how to solve the problem...
Any help is much appreciated!!!

Thank you

Excel 2010

When opening a generated xlsx file with Excel 2010 I am prompted with "Excel found unreadable content in 'test.xlsx' Do you want to recover the contents of this workbook ? If you trust the source of this workbook, click Yes".

I am using the example provided.

$header = array(
'year'=>'string',
'month'=>'string',
'amount'=>'money',
);
$data = array(
array('2003','1','-50.5'),
array('2003','5', '23.5'),
);

$writer = new XLSXWriter();
$writer->setAuthor('Doc Author');
$writer->writeSheet($data,'Sheet1',$header);
$writer->writeToFile('test.xlsx');

Phone numbers with leading + are interpreted as integer

Hi,

Phone numbers starting with + (e.g. +12345678) are interpreted as integer when the value is smaller than 32bit INT.

I think a fix could be changing:

elseif ($value{0}!='0' && filter_var($value, FILTER_VALIDATE_INT)){ //excel wants to trim leading zeros

to

elseif ($value{0}!='0' && $value{0} != '+' && filter_var($value, FILTER_VALIDATE_INT)){ //excel wants to trim leading zeros

Greetings

How do I set the color of a cell?

I absolutely love PHP_XLSXWriter, but I need to be able to set the background color of cells and I cannot figure out how to do that. I did see that there's a fork where someone has added in this capability, but their version of xlsxwriter.class.php just gives me an internal server 500 error and won't run.

composer error

Could not scan for classes inside "xlsxwriter.class.php" which does not appear to be a file nor a folder

Number stored as Text

Hi,
I was getting this error on Excel, because all data coming from mysql is inside commas:
'1', '5.1'
and XLSXWriter assumed its a string.

Tried changing the column type to 'GENERAL', but same error.
Adding this to my code:
is_numeric($value) $value=trim($value,"'");
didn't work, because Excel was giving an error when opening the file.

So I changed this line in XLSXWriter:
} else if (!is_string($value)){
to
} else if (!is_string($value) || is_numeric($value)){

and it worked :)

But is there an option without changing XLSXWriter?

Thx

Read Error: Excel found unreadable content in file.xlsx. ...

I am using XLSXWriter to write database data to an Excel spreadsheet. This is working great for 99% of the data in the database. Great job! No PHP memory errors! I do have one issue however:

I am receiving the "Excel found unreadable content in file.xlsx" message for on 25 row sub set of the data. I would be happy to send you the file in question. My database is using ISO-8859-1 encoding, but I am using mb_convert_encoding($field, 'UTF-8', 'windows-1252') to convert the strings. Any thoughts?

xlsx-error

Thanks!

Ed

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.