0
我有一张大型表格,其中包含未知数量的列,我希望能够通过下载链接将其导出到MS Excel。我之前完成了这个任务,没有任何问题。但是,那是当我有一个已知的数字或列。我目前能够成功发送数据到Excel文件。表格标题显示在表格的顶部。问题在于数据。不是将数据放置在正确的列中,而是将其全部放在第一列中。这里是我的代码部分:在PHP中将动态表格导出到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;'
我其实有后 for循环。它正确显示在页面上,但不在Excel文件中。之后,我尝试了$ FileRecord的东西,但它不起作用。 – user1504583