PHP tricks : generate an MS Excel file
By grapsus on Sunday 12 September 2010, 10:31 - Permalink
Here's the shortest and the fastest way I found to convert a CSV file to MS Excel format. It supports string and numeric fields. I hope this function can avoid you using huge Excel PHP classes which are too complicated and slow (and require reading a lot of documentation) for such a basic task.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | /* Written by Alexis Bezverkhyy <alexis@grapsus.net> in September 2010 * This is free and unencumbered software released into the public domain. * For more information, please refer to <http://unlicense.org/> */ /** Convert a CSV file to MS Excel format * * @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); } |