从php中的mysql数据库下载excel表

时间:2014-02-17 11:01:41

标签: php mysql excel

我想将mysql数据库下载到excel表。我尝试下载时出现以下错误

注意:未定义的变量:第27行的C:\ xampp \ htdocs \ admissions \ excel \ excel2.php中的数据 注意:未定义的变量:第12行的C:\ xampp \ htdocs \ admissions \ excel \ excel2.php中的标题。

我需要在标头和数据中定义的内容和位置。 这是代码

<?php
 ob_start();
 mysql_connect('localhost','root','');
 mysql_select_db('sjbhsbg');
 $sql = "SELECT * from admissions";
 $res = mysql_query($sql) or die();
 $count = mysql_num_fields($res);

 // fetch table header from database
 $header = '';
 for ($i = 0; $i < $count; $i++){
    $header .= mysql_field_name($res, $i)."\t";
    }

 // fetch data each row, store on tabular row data
 while($row = mysql_fetch_row($res)){
   $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);
  }

 $name=date('d-m-y').'-list.xls';
 header("Content-type:application/vnd.ms-excel;name='excel'");
 header("Content-Disposition: attachment; filename=$name");
 header("Pragma: no-cache");
 header("Expires: 0");

 // Output data
 echo $header."\n\n".$data;
 ?>

1 个答案:

答案 0 :(得分:0)

$query="select * from admissions";
$result = mysql_query($query) or die('Please Choose any one of the fields to export');
  //header('Content-Disposition: attachment;filename=export.csv');
$filename = $title.date("d-m-Y",time());
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
    echocsv(array_keys($row));
}
while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}