从HTML表格下载数据到excel

我有一个表,用PHP构造,显示从一个MySQL表的结果。

像这样:

$sql = mysql_query("SELECT * FROM survey"); echo "<table border='1'> <tr> <th>Question 1</th> <th>Question 2</th> <th>Question 3</th> <th>Question 4</th> <th>Question 5</th> <th>Question 6</th> <th>Question 7</th> <th>Question 8</th> <th>Question 9</th> <th>Question 10</th> <th>Question 11</th> <th>Question 12</th> <th>Question 13</th> <th>Question 14</th> <th>eMail</th> </tr>"; while ($row = mysql_fetch_array($sql)) { echo "<tr>"; echo "<td>" . $row['Question1'] . "</td>"; echo "<td>" . $row['Question2'] . "</td>"; echo "<td>" . $row['Question3'] . "</td>"; echo "<td>" . $row['Question4'] . "</td>"; echo "<td>" . $row['Question5'] . "</td>"; echo "<td>" . $row['Question6'] . "</td>"; echo "<td>" . $row['Question7'] . "</td>"; echo "<td>" . $row['Question8'] . "</td>"; echo "<td>" . $row['Question9'] . "</td>"; echo "<td>" . $row['Question10'] . "</td>"; echo "<td>" . $row['Question11'] . "</td>"; echo "<td>" . $row['Question12'] . "</td>"; echo "<td>" . $row['Question13'] . "</td>"; echo "<td>" . $row['Question14'] . "</td>"; echo "<td>" . $row['eMail'] . "</td>"; } echo "</table>"; 

我想要做的是将这个表格输出到一个excel文件中,没有任何源代码或表格标签。 有什么办法可以做到这一点? 我已经在互联网上的信息不知所措,不太清楚我需要什么。

如果可能的话,我宁愿只用PHP来完成这个工作,而不需要额外的库。

你想使用你的PHP脚本下载一个Excel文件(即PHP输出一个.xls文件),还是你想要它产生HTML输出,你可以复制/粘贴到一个Excel文件,而不会丢失格式?

如果前者,看看这个漂亮的工具

如果你只是想让它生成可以复制/粘贴到Excel的HTML,只要你的表格格式正确(并且从你的源代码中,看起来你需要在你的末尾添加一个</ tr>循环),那么你应该能够拖放它

或者,只要没有<html>标签封装它,Excel 应该足够聪明来识别HTML表格。 这篇文章解释了这个过程,但基本上你可以发送一个Excel文件(按照第一个“漂亮的工具”的build议),只需:

 header("Content-type: application/vnd.ms-excel"); echo " <table> ... </table>"; 

以及输出Excel本地格式将是相当复杂的..这就是为什么有它的库。 CSV另一方面很容易,Excel可以读取。

 $filePath = sys_get_temp_dir() . '/test.csv'; $file = fopen($filePath, '-w'); while (false !== ($row = mysql_fetch_array($sql))) { fputcsv($file, $row); } // rewind both pointers mysql_data_seek($sql, 0); fseek($file, 0); // add headers $rowForHeaders = mysql_fetch_array($sql); fputcsv($file, array_keys($rowforHeaders)); fclose($file); // to send the file via the http response header('Content-type: application/vnd.ms-excel'); header('Content-disposition: attachment; filename="mytable.csv"'); header('Content-length: '.filesize($filePath)); print file_get_contents($filePath); exit; 

你可以使用可以通过excel打开的csv(逗号分隔值):

 while ($row = mysql_fetch_array($sql)) { echo '"'. $row['Question1'] . '";'; echo '"'. $row['Question2'] . '";'; echo '"'. $row['Question3'] . '";'; echo '"'. $row['Question4'] . '";'; echo '"'. $row['Question5'] . '";'; echo '"'. $row['Question6'] . '";'; echo '"'. $row['Question7'] . '";'; echo '"'. $row['Question8'] . '";'; echo '"'. $row['Question9'] . '";'; echo '"'. $row['Question10'] . '";'; echo '"'. $row['Question11'] . '";'; echo '"'. $row['Question12'] . '";'; echo '"'. $row['Question13'] . '";'; echo '"'. $row['Question14'] . '";'; echo '"'. $row['eMail'] . '"\n'; }