php - 如何使用 PHP 将返回的数据表导出到 Excel

标签 php mysql excel

听起来很简单,但我不知道从哪里开始。

我的网站有一系列供用户选择的选项。根据该选择,构建查询,并从数据库中提取数据。然后以表格格式返回。

此时,数据已显示,用户可以单击按钮将记录导出到 Excel 工作表中。

这是查询:

 <?php 
   function displayrecords(){
   $place = $_GET['place'];
   $time = $_GET['time'];
   $name = $_GET['name'];
   $sql_json = "";
   $where = "";
   if($place != ""){
     $where = " `place` = '".mysql_real_escape_string($place)."'";
   }
   if($time != ""){
     if( $where != "" ) $where .= " AND ";
     $where .= " `time` = '".mysql_real_escape_string($time)."'";
   }
   If($name != ""){
     if( $where != "" ) $where .= " AND ";
     $where .= " `name` = '".mysql_real_escape_string($name)."'";
   }

   if ($where != "") $sql_json = "SELECT * FROM `database`" . " WHERE " . $where . ";";
   $QueryResult = @mysql_query($sql_json) or die ('<div>Use filters to search</div>');
   $resnum = mysql_num_rows($QueryResult);
   if ($resnum == 0){
     echo "<div>Your search returned no results</div";
   }
   else {
     echo "<table>\n";
     echo "<tr><th>Place</th>" . "<th>Time</th>" . "<th>Name</th></tr>\n";
     while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE){
     echo "<tr><td>{$Row[place]}</td>";
     echo "<td>{$Row[time]}</td>";
     echo "<td>{$Row[name]}</td></tr>";
   };
   echo "</table>\n";
   }
   }
   ?>

此时我可以在 html 中调用该函数:

 <?php displayrecords(); ?>

然后这是我用于导出的按钮:

 <input class="btn btn-success btn-small" type="submit" name="get_report" value="Get Report" /> 

这就是我陷入困境的地方。我知道我可能需要使用 javascript 之类的东西。请给我一些见解。无需记下我的代码。我使用常规 mysql,而不是 mysqli 或 pdo。

请告诉我接下来需要做什么才能使按钮正常工作,以便将其导出到 Excel 工作表。我将非常感谢您的帮助。

谢谢。

最佳答案

只需检查按钮是否被按下,并相应地返回 html 或 excel 数据。

   if ($resnum == 0){
     echo "<div>Your search returned no results</div";
   }
   else {
     if (isset($_POST['get_report']){
         // Use phpExcel class or just echo CSV formatted text with headers telling the browser its a CSV file
     }else{
       echo "<table>\n";
       echo "<tr><th>Place</th>" . "<th>Time</th>" . "<th>Name</th></tr>\n";
       while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE){
         echo "<tr><td>{$Row[place]}</td>";
         echo "<td>{$Row[time]}</td>";
         echo "<td>{$Row[name]}</td></tr>";
       }
   }

PHPExcel

关于php - 如何使用 PHP 将返回的数据表导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124377/

相关文章:

MySQL数据库加载到服务器

excel - #姓名? Excel 中的 VBA 函数错误

php - 使用 PHP + MySQL Left Join 合并来自 2 个查询的结果

php - 从 PUT 请求中解析 multipart/form-data

mysql - 如何根据与另一个表的匹配数据将表列设置为特定值

mysql - 将值从一个字段复制到子集中的另一个字段

excel - CSV 日期和分隔符问题

vba - 通过Excel VBA作为电子邮件附件发送的文件始终损坏

php - 一般错误 : 1267 Illegal mix of collations when filtering with a non-ASCII character

php - MySQL 函数在 PHP 中返回难以使用的结果