XLS Download from PHP Class!

January 21st, 2009 by Sean Leave a reply »

Following on from my last post on creating a proper XLS spreadsheet from PHP I have just written a small class which will do all the hard work for you if necessary.

It will handle rows and columns automatically aswell as being able to be passed an array and then generating a spreadsheet download for you.

Download: XLS from PHP Example Class (783 bytes)

Sample usage is as follows:

	//Require the file
	require_once (SHARED_CLASSES_DIR . 'xls.class.php');

	//Instantiate the class.
	$xls = new xls(); 

	//Just build an example array out of test data
	$array = array(
		array(1,2,3,4,'five')
		, array('five','test' ,4,3, 0)
	);

	//Triggers the download using the passed array
	$xls->download_from_array($array);

Note that when instantiating the class you can pass a string as an argument and it will set the name of the XLS download. No need to add .xls to the end because it will do that for you.

Download: XLS from PHP Example Class (783 bytes)

3 comments

  1. jbogdani says:

    Hello,
    thank you very much for your class witch I found very useful and fast.
    But I have an encoding problem. I use your class to export data from a MySQL DB via PHP. Both MySQL and PHP work with UTF-8 char encoding, but when I open the xls file all accentuated characters looks strange: “ën” stands for “ë”, etc. Maybe I have to specify character encoding the xls header? Could you help me in any way?
    Thank you very much

  2. Sean says:

    Hi there. Glad you are finding it useful. I used to work a lot with UTF8. We used to have to put utf8_decode() on a load of the outputs for various download and output systems. Maybe that will work?

    thanks
    Sean

  3. jbogdani says:

    Hi.
    Thank you for your help. I just changed the encoding of my data before packing them and now it works fine!
    Here it is the changed function (if anybody needs it):

    function cell($value) {
    $value=utf8_decode($value);
    if (is_numeric($value)) {
    … etc …
    }

    $this->xls_string .= $value;

    $this->col++;
    }

Leave a Reply