I am currently exporting tenant data from my MySql database to an Excel spreadsheet using the code below.
<?php
require_once('../../../includes/config.inc.php');
require_once(MYSQL);
$query = "SELECT * FROM tenant";
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";
$field_count = $result->field_count;
for ($for_count = 1; $for_count < $field_count; $for_count++)
{
$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");
while($row = $result->fetch_assoc())
{
$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);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
}
?>
The code is currently working, however I have two problems:
1) I want the columns in the spreadsheet to automate the size of the content upon creation.
2) In the data there is a field “Phone”, where numbers tend to start with 0. As a result, 0 is omitted in the database, and I think that the column should be indicated as a string.
Does anyone know how to do this? I don't want to use PHPExcel, as this seems like massive over-complication when that's all I want to do.