如何使用PHP将MySQL表导出到Excel?

时间:2015-06-18 03:49:08

标签: php mysql excel

我正在为我的学校开发一个应用程序来记录每个类的Class Cleanliness Results,所以我需要使用PHP将MySQL表中的结果转换为Microsoft Excel,最好也可以通过Android OS Phone打开。

我使用了以下PHP代码:

<?PHP

$mysqli_user = "(user)";
$mysqli_password = "(password)";
$mysqli_host = "(host)";
$mysqli_database = "(database)";


  $filename = "grading_results_" . time() . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

$link = mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password,$mysqli_database);
$query = 'SELECT * FROM (table_name)';

$result = mysqli_query($link, $query);

while ($row = mysqli_fetch_row($result)){
 print implode("\t", $row) . "\n";
}
mysqli_close($link);
?>

这就是我的表在phpMyAdmin中的样子:

https://www.dropbox.com/s/7pr3gh06zta5d8u/Snip20150618_2.png?dl=0

这是我使用此代码转换后Excel文件的样子。

https://www.dropbox.com/s/571m9lfj64tklpc/Snip20150618_3.png?dl=0

为什么没有列和行?我需要Excel文件与phpMyAdmin中的表完全相同的格式和样式。任何人都可以帮助编辑我的代码而不是为我提供全新的代码吗?

提前感谢您的回答!

3 个答案:

答案 0 :(得分:1)

手动

  1. 运行tour localhost并登录phpMyAdmin
  2. 单击您的数据库,然后单击要获取的表 Excel中。
  3. image
  4. ,然后

    1. enter image description here
    2. 然后按GO按钮
    3. 使用代码

      define ("DB_HOST", "localhost");
      define ("DB_USER", "root");
      define ("DB_PASS","");
      define ("DB_NAME","DATABASE_NAME");
      
      $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
      $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
      

      然后

      $setCounter = 0;
      
      $setExcelName = "download_excal_file";
      
      $setSql = "YOUR SQL QUERY GOES HERE";
      
      $setRec = mysql_query($setSql);
      
      $setCounter = mysql_num_fields($setRec);
      
      for ($i = 0; $i < $setCounter; $i++) {
          $setMainHeader .= mysql_field_name($setRec, $i)."\t";
      }
      
      while($rec = mysql_fetch_row($setRec))  {
        $rowLine = '';
        foreach($rec as $value)       {
          if(!isset($value) || $value == "")  {
            $value = "\t";
          }   else  {
      //It escape all the special charactor, quotes from the data.
            $value = strip_tags(str_replace('"', '""', $value));
            $value = '"' . $value . '"' . "\t";
          }
          $rowLine .= $value;
        }
        $setData .= trim($rowLine)."\n";
      }
        $setData = str_replace("\r", "", $setData);
      
      if ($setData == "") {
        $setData = "no matching records found";
      }
      
      $setCounter = mysql_num_fields($setRec);
      
      
      
      //This Header is used to make data download instead of display the data
       header("Content-type: application/octet-stream");
      
      header("Content-Disposition: attachment; filename=".$setExcelName."_Report.xls");
      header("Pragma: no-cache");
      header("Expires: 0");
      
      //It will print all the Table row as Excel file row with selected column name as header.
      echo ucwords($setMainHeader)."\n".$setData."\n";
      

      More About Code

答案 1 :(得分:0)

SELECT id, name, email INTO OUTFILE '/tmp/ram.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE id=1

此处/tmp/是您要存储csv的地址

答案 2 :(得分:-1)

  <?php
    header( "Content-Type: application/vnd.ms-excel" );
    header( "Content-disposition: attachment; filename=spreadsheet.xls" );

    // print your data here. note the following:
    // - cells/columns are separated by tabs ("\t")
    // - rows are separated by newlines ("\n")

    // for example:
    echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
    echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>

//您可以从数据库中获取数据并显示在表中。然后将表放在echo中以获取Excel文件。