I have some PHP script for export MYSQL table into Excel format, but I get some problem after the table have exported. The data which get from db just show only one row.
This the following script:
$dbc=mysql_connect(_SRV,_ACCID,_PWD) or die(_ERROR15.": ".mysql_error());
$db=mysql_select_db("qdbase",$dbc) or die(_ERROR17.": ".mysql_error());
$sQuery = "SELECT id, Line, Model,Lot_no,
COUNT( Serial_number ) AS Qty,
SUM(S), SUM(A), SUM(B), SUM(C),
(SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1) / COUNT(Serial_number) AS QP,
ROUND((SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1) / COUNT(Serial_number)*1000,2) AS PPM
FROM `inspection_report`";
$rResult = mysql_query( $sQuery) or die();
$count = mysql_num_fields($rResult);
// fetch table header
$header = '';
for ($i = 0; $i < $count; $i++){
$header .= mysql_field_name($rResult, $i)."\t";
}
// fetch data each row, store on tabular row data
while($row = mysql_fetch_row($rResult)){
$line = '';
foreach($row as $value){
if(!isset($value) || $value == ""){
$value = "\t";
}else{
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
$data = str_replace("\r", "", $data);
if ($data == "") {
$data = "\nno matching records found\n";
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");
// output data
echo $header."\n".$data;
?>
beside that, how to make some border for this table?
If youre goign to do it as an html table then i would jsut output liek you normally right a table… for example you might do:
Youre only getting one row because youre using aggregate functions without a
GROUP BYclause. Try adding aGROUP BYon on something that ties each of these “entries” to a specific group like theLot_noor whatever youre trying to report on.As far as the border, you cant do that with
CSVwhich although readbale by Excel, is not actually anExcelformat file with all the extras like formatting for borders. To use things like formatting you need to output native Excel or an html table that can be loaded into excel. Take a look atphpexcelif you need to do that.