在第一列中添加序列号,同时通过php将mysql导出为excel



我使用以下php代码通过php脚本将mysql数据导出到excel。

由于mysql表中的Id不是串行的,因为一些行是根据需要删除的。

所以我想在第一列中为mysql中的记录添加序列号。在下面的代码中可以添加什么来实现这一点?

非常感谢你的帮助。

我当前的代码如下:

<?php
include("db.php");
$file_name = "My-Records-" . date('d-F-Y-H-i-s') . ".xls";
function cleanData(&$str){
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
function modify($str) {
return ucwords(str_replace("_", " ", $str));
}
# Header information
header("Content-Disposition: attachment; filename="$file_name"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = $database->get_results("SELECT lname, fname, mobile, email, form_date FROM myTable") or die('Connection failed!');
foreach($result as $row){
if(!$flag){
// display field/column names as first row
$old_states1 = array_keys($row);
$old_states2 = array_map("modify", $old_states1);
$states = implode("t", $old_states2 ) . "rn";
print $states;
$flag = true;
}
array_walk($row, 'cleanData');
print implode("t",  array_values($row)) . "rn";
}
exit;
?>

稍微更改代码以获得您想要的:

// ...
// NEW CODE HERE
$row_index = 0;
foreach ($result as $row) {
// NEW CODE HERE
$row = array_merge(['id' => ++$row_index], $row);

if (!$flag) {
// display field/column names as first row
$old_states1 = array_keys($row);
$old_states2 = array_map("modify", $old_states1);
$states = implode("t", $old_states2 ) . "rn";
print $states;
$flag = true;
}

array_walk($row, 'cleanData');

print implode("t",  array_values($row)) . "rn";
}

完整的演示代码

最新更新