Preskoči na: glavni sadržaj | navigaciju | pretraživanje

PHP class for exporting data in multiple worksheets Excel XML

by Anorgan on January 21st, 2009.

I was trying to find the code to generate multiple worksheet Excel file, and after half an hour of searching PHP classes, blogs, forums and whatnot, decided to write the class from scratch. On the MSDN there is enough info, but one still has to figure some things out when coding the xml generator for Excel. And just a remark for MS guys – frames are out. So without further ado, here’s the class and lower, you can find the usage instructions.

excel_xml.zip

It is fairly simple to use the class to generate the XML, here are some examples:

include 'excel_xml.php';
$excel = new excel_xml();
 
/**
* Add style to your worksheet, it's reference will be "header"
* You add it as an array with the key being the modifier and the value parameter. 
* You can add:
*    - size in pt
*    - font like "Georgia"
*    - color in hex for font color
*    - bgcolor in hex for background color
*    - bold as boolean (bold => 1)
*    - italic as boolean
*    - strike as boolean
*/
 
$header_style = array(
    'bold'       => 1,
    'size'       => '12',
    'color'      => '#FFFFFF',
    'bgcolor'    => '#4F81BD'
);
 
$excel->add_style('header', $header_style);
 
/**
* Add row and attach the style "header" to it
*/
$excel->add_row(array(
    'Username',
    'First name',
    'Last name'
), 'header');
 
/**
* Add some rows, if you encapsulate the string inside asterisks,
* they will get bold using the predefined style "bold"
* If you append "|x" where x is a number, that cell will be
* merged with the x following cells
*/
$excel->add_row(array(
    'Anorgan|2'
));
 
$excel->add_row(array(
    '*Marin*',
    'Crnković'
));
 
/**
* You don't like the arrays, or already have
* some form of csv generating script that uses strings?
* No biggie, just delimit the string with ";" or ","
*/
$excel->add_row('Some number:;12');
 
/**
* Tell the object to create the worksheet.
* The passed string is the name of the worksheet
*/
$excel->create_worksheet('Users');
 
/**
* If you invoke the generate method, you will get the
* XML returned or...
*/
$xml = $excel->generate();
 
/**
* ... you can pass the whole thing for download with
* the passed string as the filename
*/
$excel->download('Download.xml');
  1. #1 Danijel February 10th, 2009

    it is interesting how no one wants to comment “proffesional” posts like this. with programming themes.

  2. #2 Eric Faerber February 12th, 2009

    Thank you very much for this script!

    There is a bug with the styles. excel_xml::add_style is never called. My fix is changing the code in excel_xml::prepare_cell

    // Formating: bold
    if(!is_null($style)) {
        $style_id = 's' . (sizeof($this->styles) + 1);
        $this->add_style($style_id, $style);
        $style = ' ss:StyleID="'.$style_id.'"';
    } elseif (preg_match('/^\*([^\*]+)\*$/', $str, $out)) {
        $style  = ' ss:StyleID="bold"';
        $str    = $out[1];
    }
  3. #3 Danijel February 17th, 2009

    stavite captchu, protiv spamanja :)

  4. #4 lekke February 22nd, 2009

    Just turned on Akismet, hopefully there will be no need for a captcha.

  5. #5 Andrew Kaddas March 6th, 2009

    Nice script. Very well documented. Cheers

  6. #6 Jeronimo Martinez March 23rd, 2009

    Pretty good script, other options that i try are expensive(specially phpexcel) in the resources usage (memory and cpu), cheers

  7. #7 gkatz June 12th, 2009

    Really useful script!!!
    Thank you very much Anorgan.

    Only one question, why do you use “preg_match” to decide whether a value is Number or String? You could just use “is_numeric”. In fact using “preg_match” is a problem since it doesn’t recognize decimal numbers as Number. For example if you try to give “23.5″ as a value for a cell it will be stored as string. If you replace:
    $type = preg_match(’/^([\d]+)$/’, $str) ? ‘Number’ : ‘String’;
    with:
    $type = is_numeric($str) ? ‘Number’ : ‘String’;
    it works fine.

    Still thank you very much for the script.

  8. #8 Anorgan June 30th, 2009

    @gkatz:
    Thank you for your comment! I did consider it, and opted for my solution just because some numers can be formated as “23.5″, some as “23,5″ (comma), and some “12.324,53″. The last 2 numbers “behave” better as strings in Excel, and the letter produces an error if presented as “Number” to Excel. I think that it is safer to present “wierd” formated numbers as “String”.

  9. #9 geme4472 July 23rd, 2009

    Hello,

    Awesome script. Love the documentation and style–completely readable–and therefore usable!

    I had to make a slight mod to get multiple worksheets working. The code uses implode (join) to glue worksheets with an empty string, but proper xml requires a linebreak, so the whole of my changes are (line 57)

    From:
    $xml .= join(”, $this->worksheets).$this->nl;

    To:
    $xml .= join(”\n”, $this->worksheets).$this->nl;

  10. #10 Mhammad July 29th, 2009

    there are alot of bugs in this but thanks for the xml part bro

  11. #11 Prakash September 30th, 2009

    Hello

    Can you send me an example exporting mysql data,

    I have used this example, I used while loop for getting records from mysql and used $excel->add_row($data). But file not loading and shows the following error in C:\Documents and Settings\dprakash\Local Settings\Temporary Internet Files\Content.MSO/filename.

    XML PARSE ERROR: Missing end-tag
    Error occurs at or below this element stack:

    Please advice me on this.

    Thanks in Advance.

  12. #12 jooria January 6th, 2010

    what about add it here http://www.jooria.com/scripts/PHP-Class-Scripts-129/

  13. #13 ansh February 9th, 2010

    well this scipts works fine when there is small amount of data. but when i tried to export 4522 records it throughs the error of memory limit i tried setting it to even 900M still it does not seems to be working any solution?

  14. #14 Chris Wanamaker February 26th, 2010

    Love the class! It was exactly what I was looking for. I was wondering though, is there a way to save the XLS file to a folder on the server instead of downloading it to a local machine?

  15. #15 Onious April 8th, 2010

    Awesome script…

  16. #16 Madhab Nath April 12th, 2010

    Very useful script, specially the documentation. It helps me lot. Thanks and cheers..

  17. #17 sisingamangaraja May 6th, 2010

    thank’s alot for your script and the documentation. cheerrss..

  18. #18 Tony June 3rd, 2010

    thanks for providing this. it saved me a lot of time. just added it to the concrete5 stats package: http://inneroptics.net/concrete5/stats/

  19. #19 Tony June 4th, 2010

    the bug fix on comment #9 was required for me to get this working.

  20. #20 mawek September 29th, 2010

    thank’s alot for the script. its help me alot…yeah!!

  21. #21 Samer January 16th, 2011

    thanks for providing this.
    but i need to ask you about using create table function.
    and how can i create a table with cells border.
    please help.

  22. #22 Sandeep February 28th, 2011

    Excellent script, really very helpful :)
    Can I add an image through this script? Please confirm. If not, I’ll have to work on some other script from scratch again :(

  23. #23 santi March 3rd, 2011

    Thank you very much. Excellent script. It just solved my problem to create a multi-sheet excel file easily.

  24. #24 samuel prasetya May 20th, 2011

    You save my day man …

    Thanks a lot Anorgan, this script is far less painful than others i had found after a half day digging.

    Very good …

  25. #25 Freddie May 31st, 2011

    Hi, It only give with one sheet, when i change this code

    $excel->download(’Download.xls’);

    It give me excel file with only one sheet ‘user’, I tried to create another sheet by duplicating $excel->create_worksheet(’Users_new’); but end up excel error, cannot open the file.

    please help.

    Freddie

  26. #26 Freddie May 31st, 2011

    Sorry for the first comment. Now I can generate with multiple sheet.

    Can I ask you, is there anyway to just print html code to spreadsheet?

    Coz My report is very complicated.

    Thanks

  27. #27 Billy June 3rd, 2011

    Can anyone please give me a simple example with two sheets, thx !

  28. #28 Felipe June 20th, 2011

    Hi thanks for sharing your knowlegde, is not your obligation but I will really appreciate if you can give me some advice.
    I’m trying to make your example work by enclosing it between php brackets; when I try to open the generated file excell (excell 2003 eng) crashes; any ideas why?
    Thanks in advance

  29. #29 Toby July 14th, 2011

    Hi, thanks for the script!

    would appreciate an example for filling two worksheets as well… thx!

  30. #30 Hiram Ferran September 6th, 2011

    Thanks so much for providing individuals with an exceptionally splendid opportunity to discover important secrets from this web site.

  31. #31 Ohana October 17th, 2011

    does this even work? where is this class and hes methods declared?

  32. #32 Transformers Games November 12th, 2011

    I view something genuinely special in this website .

  33. #33 Louie November 25th, 2011

    thank you for this script

  34. #34 praba January 4th, 2012

    Hai

    this is nice script, Good job

  35. #35 sports betting January 13th, 2012

    Random Google results can lead to fantastic blogs like this. You are doing a good job, and we share lots of thoughts.

  36. #36 christian louboutin January 14th, 2012

    I am glad to be a visitant of this everlasting website ! , regards for this rare information! .

  37. #37 Arun January 25th, 2012

    Hi,
    I have used this script.It saved me a lot of time..But one issue i am facing is When i tried to Download the file in IE i am getting an error and the file s not loaded it is HTTPS site.
    I am getting the below error.
    Error: Unable to download this from internet site.

Speak your mind

Preskoči na: glavni sadržaj | navigaciju | pretraživanje