[英]Exporting a dynamic table to Excel in PHP
我有一个很大的表,其中的列数未知,我希望能够通过下载链接导出到MS Excel。 我之前没有做过这个。 但是,那是我有一个已知数字或列的时候。 我目前能够成功将数据发送到Excel文件。 表格标题正确显示在表格顶部。 问题出在数据上。 而不是将整个页面上的数据放在正确的列中,而是将所有数据都放在第一列中。 这是我的代码的一部分:
while($row = mysql_fetch_row($result))
{
// Loops through the results
for($i=0; $i < $num_cols; $i++)
{
// Prints out the data in a table cell
echo("<Td class='data'>$row[$i]</Td>");
$FileRecord = Array($row[$i]);
$exportFile->Export_Record($FileRecord);
}
}
通常我会执行$FileRecord = Array($row[0], $row[1], ..., $row[n])
并且一切正常,但是如果不确定,我不确定该怎么做有多少列。 任何帮助将是巨大的!
我没有使用任何图书馆。 $exportFile
来自我正在使用的函数。 看起来像这样:
class CSV_File {
private $out='';
private $name='';
private $column_names="";
private $count = 0;
//Creates the file name and the header columns
function __Construct($buf, $names) {
$GLOBALS["name"] = $buf;
$GLOBALS["column_names"] = ($names."\n");
}
public function Export_Record($array) {
if (!is_array($array))
throw new Exception("NOT AN ARRAY");
for ($i = 0; $i <= count($array); $i++) {
$GLOBALS["out"] .= $array[$i];
if ($i < count($array)-1) {
$GLOBALS["out"] .= ",";
}
}
$GLOBALS["out"] .= "\n";
$GLOBALS["out"]++;
}
public function ExportButton($align) {
$output = $GLOBALS["out"];
$filename = $GLOBALS["name"];
$columns = $GLOBALS["column_names"];
if ($align == null)
$align = "align";
echo(" <$align><form name=\"export\" action=\"export.php\" method=\"post\">
<button type=\"submit\" style='border: 0; background: transparent; font-size: 12px;font-weight:bold;'>
<img src = 'images/icon_csv.png' width = '16' height ='16' alt ='Download Data'> Download</button>
<input type=\"hidden\" value=\"$columns\" name=\"csv_hdr\">
<input type=\"hidden\" value=\"$filename\" name=\"fileprefix\">
<input type=\"hidden\" value=\"$output\" name=\"csv_output\">
</form></align>");
}
}
然后export.php看起来像这样:
if (isset($_POST['csv_hdr']))
{
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_output']))
{
$out .= $_POST['csv_output'];
}
if (isset($_POST['fileprefix']))
{
$fname .= $_POST['fileprefix'];
}
//Now we're ready to create a file. This method generates a filename based on the current date & time.
$filename = $fname."_".date("Y-m-d_H-i",time());
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;'
那不是Excel表格。 这是一个HTML表,您刚好将其馈入Excel。
您的问题是您没有为要获取的每条记录开始一个新的表行,因此所有内容都只成为第一行中的一个新单元格。
你需要类似的东西
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach($row as $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.