我目前正在使用以下代码将MySql数据库中的tenant数据导出到Excel电子表格中。
<?php
require_once('../../../includes/config.inc.php');
require_once(MYSQL);
$query = "SELECT * FROM tenant"; //Define the SQL query
if ($result = $dbc->query($query))
{
$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=tenant_data.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");
$seperator = "'t"; //define separator (defines columns in excel)
$field_count = $result->field_count;
for ($for_count = 1; $for_count < $field_count; $for_count++) //start of printing column names as names of MySQL fields
{
$result->field_seek($for_count);
$field_info = $result->fetch_field();
$field_name = $field_info->name;
$field_name_title = str_replace("_", " ", "$field_name");
$field_array[] = $field_name;
echo $field_name_title . $seperator;
}
$result->field_seek(0);
print("'n"); //end of printing column names
while($row = $result->fetch_assoc()) //start while loop to get data
{
$schema_insert = "";
for ($col_count = 0; $col_count < $field_count - 1; $col_count++)
{
$current_field = $field_array[$col_count];
if ($row[$current_field] != "")
{
$schema_insert .= "$row[$current_field]" . $seperator;
}
else
{
$schema_insert .= "" . $seperator;
}
}
$schema_insert = str_replace($seperator . "$", "", $schema_insert);
$schema_insert = preg_replace("/'r'n|'n'r|'n|'r/", " ", $schema_insert); //Replaces 'n or 'r with a space
$schema_insert .= "'t";
print(trim($schema_insert));
print "'n";
}
}
?>
代码目前可以工作,但我有两个问题:
1) 我希望电子表格中的列在创建时自动调整为内容的大小。
2) 在数据中,有一个"电话"字段,其中的数字往往以0开头。因此,数据库中的0往往会丢失,我认为该列需要指定为String。
有人知道如何做这两件事吗?我不想使用PHPExcel,因为这似乎是一个巨大的过度复杂化,而这正是我想要做的。
在没有任何答案的情况下,我最终决定只使用PHPExcel类。