Generate MS Excel File From PHP

by Dinesh 2012-05-29 15:06:27

/** Generate MS Excel File From PHP
*
* @param string $in input file
* @param string $out output
* @param string $glue CSV glue
* @param string $enclosure CSV enclosure character
*/
function csv2xls($in, $out, $glue=";", $enclosure='"')
{
$fp_in = fopen($in, "r");
$fp_out = fopen($out, "w");

/* write Excel BOF */
fputs($fp_out, pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0));

/* Read CSV fields */
for($row = 0; $fields = fgetcsv($fp_in, 0, $glue, $enclosure); $row++)
{
foreach($fields as $col=>$value)
{
$value = trim($value);
$value = utf8_decode($value);

/* string cell */
if(!is_numeric($value))
{
$l = strlen($value);
fputs($fp_out,
pack("ssssss", 0x204, 8 + $l, $row, $col, 0x0, $l).$value);
}
/* numeric cell */
else
{
fputs($fp_out,
pack("sssss", 0x203, 14, $row, $col, 0x0).pack("d", $value));
}
}
}

/* write Excel EOF */
fputs($fp_out, pack("ss", 0x0A, 0x00));

fclose($fp_out);
fclose($fp_in);
}

Tagged in:

1070
like
0
dislike
0
mail
flag

You must LOGIN to add comments