PHP export MySQL database to Excel table _php Tutorial

Source: Internet
Author: User
Using PHP to export MySQL database for Excel table Many ways, the simplest directly using the PHP fputcsv function, there is a direct input CSV format is also possible, to generate Excel standard format we need to use a third-party plug-in

Method one, using Fputcsv

The code is as follows Copy Code


Output Excel file header, you can replace user.csv with the file name you want
Header (' Content-type:application/vnd.ms-excel ');
Header (' content-disposition:attachment;filename= ' user.csv "');
Header (' cache-control:max-age=0 ');

Get the data from the database, in order to save memory, do not read the data once to the memory, the subordinate handle in a row to read
$sql = ' SELECT * from tbl where ... ';
$stmt = $db->query ($sql);

Open PHP file handle, php://output direct output to browser
$fp = fopen (' php://output ', ' a ');

Output Excel Column name information
$head = Array (' name ', ' gender ', ' age ', ' Email ', ' phone ', ' ... ');
foreach ($head as $i = = $v) {
CSV Excel support GBK encoding, be sure to convert otherwise garbled
$head [$i] = iconv (' utf-8 ', ' GBK ', $v);
}

Writes data to a file handle via Fputcsv
Fputcsv ($fp, $head);

Counter
$cnt = 0;
Every $limit line, refresh the output buffer, not too big, not too small
$limit = 100000;

Row-by-line data extraction without wasting memory
while ($row = $stmt->fetch (zend_db::fetch_num)) {

$cnt + +;
if ($limit = = $cnt) {//Refresh output buffer to prevent problems caused by excessive data
Ob_flush ();
Flush ();
$cnt = 0;
}

foreach ($row as $i = = $v) {
$row [$i] = iconv (' utf-8 ', ' GBK ', $v);
}
Fputcsv ($fp, $row);
}

Method two, output CSV format data directly in the browser with header

The code is as follows Copy Code

/* Connect to Database */
$DB _server = "localhost";
$DB _username = "root";
$DB _password = "123456";
$DB _dbname = "MyDB"; Target database name
$DB _tblname = "MyTable"; Target table name
$Connect = @mysql_connect ($DB _server, $DB _username, $DB _password) or Die ("couldn ' t Connect.");
mysql_query ("Set Names ' UTF8 '");

$savename = Date ("Ymjhis"); Export Excel file name
$file _type = "Vnd.ms-excel";
$file _ending = "xls";
Header ("content-type:application/$file _type;charset=utf8");
Header ("content-disposition:attachment; Filename= ". $savename.". $file _ending ");
Header ("Pragma:no-cache");

/* Write Note information */
$now _date = Date ("Y-m-j h:i:s");
$title = "Database name: $DB _dbname, Data sheet: $DB _tblname, Backup date: $now _date";
Echo ("$titlen");

/* Query Database */
$sql = "SELECT * from $DB _tblname";
$ALT _db = @mysql_select_db ($DB _dbname, $Connect) or Die ("couldn ' t Select Database");
$result = @mysql_query ($sql, $Connect) or Die (Mysql_error ());

/* Write table field name */
for ($i = 0; $i < Mysql_num_fields ($result); $i + +) {
Echo Mysql_field_name ($result, $i). ",";
}
echo "n";

/* Write table Data */
$sep = ", T";
while ($row = Mysql_fetch_row ($result)) {
$data = "";
for ($i =0; $i
if (!isset ($row [$i]))
$data. = "NULL". $sep; Working with NULL fields
ElseIf ($row [$i]! = "")
$data. = "$row [$i]". $sep;
Else
$data. = "". $sep; Working with empty fields
}
echo $data. " n ";
}
?>

Example 3, the second one's almost there.

The code is as follows Copy Code


Search
$start _time = strtotime ($start _date);
$end _time = strtotime ($end _date);
$sql = "Select A.*,b.order_amount,b.money_paid from". $ecs->table (' Invoice '). "As a".
"LEFT join". $ecs->table (' Order_info '). "As B on A.order_id=b.order_sn".
"Where A.add_time >=". $start _time. "and A.add_time <=". $end _time. " ";
$temp _list = $db->getall ($sql);

if ($temp _list) {//have data
$Html = ". Chr (10);
$Html. = '



















<>





$temp _time = Date (' y-m-d ', $temp _list[$i [' add_time ']);
$Html. = '














';Get an array that matches the criteriafor ($i =0; $i$temp _i = $i +1;if ($temp _list[$i][order_amount]==0) {$temp _money = $temp _list[$i][money_paid];}else{$temp _money = $temp _list[$i][order_amount];} ';}$Html. = '
Time: '. $start _date. ' ~ '. $end _date. '
Number Invoice type Invoice Header Invoice content Order number Amount Add date Recipient Contact information Address
'. $temp _i. ' '. $temp _list[$i][type_name]. ' '. $temp _list[$i][top]. ' '. $temp _list[$i][content]. ' '. $temp _list[$i][order_id]. ' '. $temp _money. ' '. $temp _time. ' '. $temp _list[$i][user_name]. ' '. $temp _list[$i][mobile]. ' '. $temp _list[$i][tel]. ' '. $temp _list[$i][address]. '
';
$Html. = '';
$mime _type = ' application/vnd.ms-excel ';
Header (' Content-type: '. $mime _type);
Header (' content-disposition:attachment; filename= ' Invoice.xls ');
Header (' Cache-control:must-revalidate, post-check=0, pre-check=0 ');
Header (' Pragma:public ');
Echo $Html;

Sometimes Excel will automatically convert the number format, so some mobile phone numbers, identity cards and so on is messy, so you can export, the first defined

The code is as follows Copy Code

'. $temp _list[$i][order_id]. '

http://www.bkjia.com/PHPjc/632921.html www.bkjia.com true http://www.bkjia.com/PHPjc/632921.html techarticle using PHP to export MySQL database for Excel table Many ways, the simplest directly use PHP fputcsv function, there is the direct input CSV format is also possible, to generate Excel standard grid ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.