【发布时间】:2015-07-24 01:27:33
【问题描述】:
我正在将数据从 MySQL 数据库导出到 Excel 电子表格中。我之前已经找到了执行此操作的代码,并且效果很好。它不会格式化电子表格。它也是我创建的第一个 PHP/MySQL 站点,数据不需要很漂亮。当前项目需要格式化数据。
昨天,我发现一篇文章可能让我可以做我需要做的事情。像个白痴一样,我没有复制链接。今天找不到了。
这是我的代码 -
<?php
require_once("includes/connection.php");
require_once("includes/functions.php");
// set $closed to 0 for development
$closed = 0;
//create a sting to allow the user to see if s/he is looking at open or closed items
if ($closed) {
$filename = FILENAME."_closed";
} else {
$filename = FILENAME."_open";
}
// $data will hold the result
$data = '<table>';
// is the row a header?
$th = FALSE;
// define the separator character
$sep = '\t';
// array for keys
$thKey = array();
// are we in the first row?
$firstRow = TRUE;
// create the query
$query = "SELECT ";
$query .= "training_requirements.Training, mechanism.mechName, location.locationName, impacted_employees.groupName, ";
$query .= "training_requirements.DateReceived, training_requirements.DateStart, training_requirements.DateDue, ";
$query .= "requester.lastName, requester.firstName, impact.impactName, training_requirements.TimeNeeded, ";
$query .= "priority.priority, training_requirements.Notes ";
$query .= "FROM ";
$query .= "training_requirements, impact, impacted_employees, location, mechanism, requester, priority ";
$query .= "WHERE impact.impactId = training_requirements.impactId ";
$query .= "AND impacted_employees.groupId = training_requirements.impEmpId ";
$query .= "AND location.locationId = training_requirements.trainLocId ";
$query .= "AND mechanism.mechId = training_requirements.mechId ";
$query .= "AND requester.requesterId = training_requirements.requesterId ";
$query .= "AND priority.id = training_requirements.Priority ";
$query .= "AND training_requirements.Closed = $closed ";
$query .= "AND training_requirements.Deleted = 0";
// run the query
$result = executeQuery($connection, $query);
// process the query
if (mysqli_num_rows($result) > 0) {
while ($resource = mysqli_fetch_assoc($result)) {
if (empty($thKey)) {
foreach($resource as $key => $value) {
$thKey[] = $key;
}
}
$data .= '<tr>';
for ($i = 0; $i < count($resource); $i++) {
if ($firstRow) {
// create the header
for ($j = 0; $j < count($resource); $j++) {
$data .= '<th>';
$data .= $thKey[$j];
$data .= '</th>';
}
$data .= '</tr><tr>';
$firstRow = FALSE;
}
$data .= '<td>';
if (isset($resource[$thKey[$i]])) {
$data .= $resource[$thKey[$i]];
} else {
$data .= ' ';
}
$data .= '</td>';
}
$data .= '</tr>';
}
$data .= '</table>';
echo $data;
}
//header('Content-type: application/excel');
//header("Content-Disposition: attachment; filename={$filename}.xls");
//header("Pragma: no-cache");
//header("Expires: 0");
?>
代码继续允许我在浏览器中显示结果。我在 Firefox 中得到了一个合适的表格。当我取消注释底部的标题语句时,我得到一个空白的 Excel 文件。没有细胞,什么都没有。
使用 Excel 2007(12.0.6715.5000) SP3 MSO (12.0.6721.5000)、PHP 5.4.24 和 MySQL 5.5.40。使用插件和库不是一种选择。
维恩
【问题讨论】:
-
问题是什么?
-
您没有生成 excel 文件。你正在生成 html 并且谎称它是 excel ......而且你也只是假设查询成功。如果它不返回任何行,或者完全失败,则什么也不输出。