1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Export Mysql table data to Excel spreadsheet

Discussion in 'PHP' started by BT Buses, Dec 19, 2008.

  1. #1
    G'day

    I'm requiring a script that will export certain fields from my mysql database table to excel.
    I've read up on a whole pile of snippets & codes and came across one that worked, but it converted it to a csv format, and had all the fields in the one column.
    And as I have no idea what so ever on this, I am needing help please.

    first, i want to export certain fields only:
    name, email, address, phone, mobile
    secondly, i want it to export in such a way that it will display correctly into the excel sheet (ie, correct field data in correct columns) without the need to do then import a csv into excel (if that makes any sense, as the script is being designed for somebody else with very limited computer knowledge).

    Here is the script that I found on the net as mentioned above that exports to a csv file, but all fields, and not just certain ones:

    <?php
    $host = 'localhost';
    $user = 'user';
    $pass = 'password';
    $db = 'database';
    $table = 'table';
    $file = 'export';
    
    $filename = $file."_".date("Y-m-d"); 
    
    $link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
    mysql_select_db($db) or die("Can not connect.");
    
    $result = mysql_query("SHOW COLUMNS FROM ".$table."");
    $i = 0;
    if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
    $csv_output .= $row['Field']."; ";
    $i++;
    }
    }
    $csv_output .= "\n";
    
    $values = mysql_query("SELECT * FROM ".$table."");
    while ($rowr = mysql_fetch_row($values)) {
    for ($j=0;$j<$i;$j++) {
    $csv_output .= $rowr[$j]."; ";
    }
    $csv_output .= "\n";
    }
    
    $filename = $file."_".date("Y-m-d_H-i",time());
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$filename.".csv");
    print $csv_output;
    exit;
    ?>
    PHP:
    So any help is gratefully appreciated - please!
     
    BT Buses, Dec 19, 2008 IP
  2. Sharpwebhosting

    Sharpwebhosting Member

    Messages:
    198
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    28
    #2
    you could try a program such as "Excel MySQL Conversion software 3.0" its designed to do what you are looking to accomplish.
     
    Sharpwebhosting, Dec 19, 2008 IP
  3. BT Buses

    BT Buses Peon

    Messages:
    20
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'm more so in preference to having a link on the website for the authorised member to click. Although it will be an option if nobody is able to help.
    Although after making this thread (although I searched first but said i didn't have enough search terms), I found another script, and have edit what I have above to this to atleast get just the particular fields, but still each record show in one cell, with extra ; (thanks to figo2476 who originally posted the script)

    <?php
    $host = 'localhost';
    $user = 'user';
    $pass = 'password';
    $db = 'database';
    $table = 'table';
    $file = 'export';
    
        $fields = "username, name, email, address, phone, mobile"; // the fields in the table you want. seperated with comma. Example ($fields = "field1, field2, field3";)
    
    $filename = $file."_".date("Y-m-d"); 
    
    $link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
    mysql_select_db($db) or die("Can not connect.");
    
    $result = mysql_query("SHOW COLUMNS FROM ".$table."");
    $i = 0;
    if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
    $csv_output .= $row['Field']."; ";
    $i++;
    }
    }
    $csv_output .= "\n";
    
    $values = mysql_query("SELECT $fields FROM ".$table."");
    while ($rowr = mysql_fetch_row($values)) {
    for ($j=0;$j<$i;$j++) {
    $csv_output .= $rowr[$j]."; ";
    }
    $csv_output .= "\n";
    }
    
    $filename = $file."_".date("Y-m-d_H-i",time());
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$filename.".csv");
    print $csv_output;
    exit;
    ?>
    
    PHP:
    As mentioned, would prefer to have a script rather than use external stuff *at the moment*...
     
    BT Buses, Dec 19, 2008 IP
  4. onlywin

    onlywin Greenhorn

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    18
    #4
    select * into outfile '/tmp/some_file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' from tabla_db;

    Is not exactly an excel file, it's a CSV file but if you open with excel it works perfect.
    Just be carefully with ' or " in your database contents.
     
    onlywin, Dec 19, 2008 IP
  5. MC_delta_T

    MC_delta_T Member

    Messages:
    38
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #5
    you can try this code

    <?php
    
    /**
     * Simple excel generating from PHP5
     * 
     * This is one of my utility-classes.
     * 
     * The MIT License
     * 
     * Copyright (c) 2007 Oliver Schwarz
     * 
     * Permission is hereby granted, free of charge, to any person
     * obtaining a copy of this software and associated documentation
     * files (the "Software"), to deal in the Software without
     * restriction, including without limitation the rights to use,
     * copy, modify, merge, publish, distribute, sublicense, and/or
     * sell copies of the Software, and to permit persons to whom the
     * Software is furnished to do so, subject to the following
     * conditions:
     *
     * The above copyright notice and this permission notice shall be
     * included in all copies or substantial portions of the Software.
     * 
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
     * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
     * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
     * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
     * OTHER DEALINGS IN THE SOFTWARE.
     *
     * @package Utilities
     * @author Oliver Schwarz <oliver.schwarz@gmail.com>
     * @version 1.0
     */
    
    /**
     * Generating excel documents on-the-fly from PHP5
     * 
     * Uses the excel XML-specification to generate a native
     * XML document, readable/processable by excel.
     * 
     * @package Utilities
     * @subpackage Excel
     * @author Oliver Schwarz <oliver.schwarz@vaicon.de>
     * @version 1.0
     *
      * @todo Add error handling (array corruption etc.)
     * @todo Write a wrapper method to do everything on-the-fly
     */
    class Excel_XML
    {
    
        /**
         * Header of excel document (prepended to the rows)
         * 
         * Copied from the excel xml-specs.
         * 
         * @access private
         * @var string
         */
        private $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?\>
    <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"
     xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
     xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
     xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
    
        /**
         * Footer of excel document (appended to the rows)
         * 
         * Copied from the excel xml-specs.
         * 
         * @access private
         * @var string
         */
        private $footer = "</Workbook>";
    
        /**
         * Document lines (rows in an array)
         * 
         * @access private
         * @var array
         */
        private $lines = array ();
    
        /**
         * Worksheet title
         *
         * Contains the title of a single worksheet
         *
         * @access private 
         * @var string
         */
        private $worksheet_title = "Table1";
    
        /**
         * Add a single row to the $document string
         * 
         * @access private
         * @param array 1-dimensional array
         * @todo Row-creation should be done by $this->addArray
         */
        private function addRow ($array)
        {
    
            // initialize all cells for this row
            $cells = "";
    
            // foreach key -> write value into cells
            foreach ($array as $k => $v):
    
                $cells .= "<Cell><Data ss:Type=\"String\">" . utf8_encode($v) . "</Data></Cell>\n"; 
    
            endforeach;
    
            // transform $cells content into one row
            $this->lines[] = "<Row>\n" . $cells . "</Row>\n";
    
        }
    
        /**
         * Add an array to the document
         * 
         * This should be the only method needed to generate an excel
         * document.
         * 
         * @access public
         * @param array 2-dimensional array
         * @todo Can be transfered to __construct() later on
         */
        public function addArray ($array)
        {
    
            // run through the array and add them into rows
            foreach ($array as $k => $v):
                $this->addRow ($v);
            endforeach;
    
        }
    
        /**
         * Set the worksheet title
         * 
         * Checks the string for not allowed characters (:\/?*),
         * cuts it to maximum 31 characters and set the title. Damn
         * why are not-allowed chars nowhere to be found? Windows
         * help's no help...
         *
         * @access public
         * @param string $title Designed title
         */
        public function setWorksheetTitle ($title)
        {
    
            // strip out special chars first
            $title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);
    
            // now cut it to the allowed length
            $title = substr ($title, 0, 31);
    
            // set title
            $this->worksheet_title = $title;
    
        }
    
        /**
         * Generate the excel file
         * 
         * Finally generates the excel file and uses the header() function
         * to deliver it to the browser.
         * 
         * @access public
         * @param string $filename Name of excel file to generate (...xls)
         */
        function generateXML ($filename)
        {
    
            // deliver header (as recommended in php manual)
            header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
            header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
    
            // print out document to the browser
            // need to use stripslashes for the damn ">"
            echo stripslashes ($this->header);
            echo "\n<Worksheet ss:Name=\"" . $this->worksheet_title . "\">\n<Table>\n";
            echo "<Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"110\"/>\n";
            echo implode ("\n", $this->lines);
            echo "</Table>\n</Worksheet>\n";
            echo $this->footer;
    
        }
    
    }
    
    ?>
    PHP:
     
    MC_delta_T, Dec 20, 2008 IP
  6. Yesideez

    Yesideez Peon

    Messages:
    196
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I think that's because CSV files by default are comma delimited and not semi-colon.

    Edit these two lines and try it again:
    $csv_output .= $row['Field'].",";
    PHP:
    $csv_output .= $rowr[$j].",";
    PHP:
    I'm running Excel 2007 and just saved a CSV file out to see what it looked like and I'm right - it's a comma.

    Try that - if it doesn't work let me know and I'll write and test something myself then post the code for you.

    EDIT: I've just had another look at the code and noticed a couple mistakes which could also be why it is failing - as mentioned - if you want I can write a small script for you that I know works.
     
    Yesideez, Dec 20, 2008 IP
  7. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #7
    http://danltn.com/bin/bxv.phps

    Knock yourself out, it's really nice code IMO.
    (Doesn't send headers btw, but I'm sure you can do that yourself by now ;))
     
    Danltn, Dec 20, 2008 IP
  8. BT Buses

    BT Buses Peon

    Messages:
    20
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Ah terrific, thanks for that. In fact, I like your code better as its much more simpler and easier to understand.

    I found some code finally on the net last night (must've typed in the right search terms into google), and it came out something very similar to that.

    Ok, my next question though is, a couple of the fields are numeric (like the username) and are a min of 3 digits, so if it is 10, it really is 010. How do I get it that when it writes it that it will stay as a 3 digit number rather than when opening excel to have to then edit it, thats if its possible?
     
    BT Buses, Dec 20, 2008 IP
  9. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #9
    Use str_pad.
     
    Danltn, Dec 21, 2008 IP