Exporting data from php to excel

后端 未结 5 440
逝去的感伤
逝去的感伤 2020-12-08 22:23

I need to export data from php (data retrieved from mysql database) to excel. I\'m using Zend Framework. I need to do some changes to my data before exporting to excel. Actu

5条回答
  •  时光取名叫无心
    2020-12-08 22:43

    With a bit of google you would have found this: http://www.the-art-of-web.com/php/dataexport/

    Preparing the data

    $data = array(
        array( "firstname" => "Mary", "lastname" => "Johnson", "age" => 25 ),
        array( "firstname" => "Amanda", "lastname" => "Miller", "age" => 18 ),
        array( "firstname" => "James", "lastname" => "Brown", "age" => 31 ),
        array( "firstname" => "Patricia", "lastname" => "Williams", "age" => 7 ),
        array( "firstname" => "Michael", "lastname" => "Davis", "age" => 43 ),
        array( "firstname" => "Sarah", "lastname" => "Miller", "age" => 24 ),
        array( "firstname" => "Patrick", "lastname" => "Miller", "age" => 27 )
    );
    

    The first step is to output the data in a tab-delimited format (CSV can also be used but is slightly more complicated). To achieve this we use the following code:

    
    

    We set the content type to text/plain so that the output can more easily be viewed in the browser. Otherwise, because there is no HTML formatting, the output would appear as a single line of text.

    The first line of output will be the column headings (in this case the field names are used). Values are separated with a tab \t and rows with a line break \n. The output should look something like the following:

    firstname  lastname  age
    Mary Johnson 25 
    Amanda Miller 18 
    James Brown 31 
    Patricia    Williams     7 
    Michael Davis 43 
    Sarah Miller 24 
    Patrick Miller 27
    

    There's already a weakness in this code that may not be immediately obvious. What if one of the fields to be ouput already contains one or more tab characters, or worse, a newline? That's going to throw the whole process out as we rely on those characters to indicate column- and line-breaks.

    The solution is to 'escape' the tab characters. In this case we're going to replace tabs with a literal \t and line breaks with a literal \n so they don't affect the formatting:

    
    

    Now, before each row is echoed any tab characters are replaced "\t" so that our columns aren't broken up. Also any line breaks within the data are replaced with "\n".

提交回复
热议问题