Created
December 8, 2014 10:05
-
-
Save troelskn/cf9df474662c88ba7951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Write with file extension xls and you should be fine. | |
* This format is called SpreadsheetML | |
*/ | |
class SimpleXlsWriter { | |
protected $filename; | |
protected $handle; | |
protected $title = "No Title"; | |
protected $author = "No Author"; | |
protected $headerWritten = false; | |
function __construct($filename) { | |
$this->filename = $filename; | |
$this->handle = fopen($filename, 'w'); | |
} | |
function setAuthor($author) { | |
$this->author = $author; | |
} | |
function setTitle($title) { | |
$this->title = $title; | |
} | |
function getFilename() { | |
return $this->filename; | |
} | |
function writeHeader($row) { | |
$this->writeRow($row, true); | |
} | |
function writeRow($row, $header = false) { | |
$tmp = array(); | |
foreach ($row as $column) { | |
$type = is_numeric($column) ? 'Number' : 'String'; | |
$tmp[] = ' <Cell><Data ss:Type="'.$type.'">' . str_replace("\r\n", " ", htmlspecialchars($column)) . "</Data></Cell>\n"; | |
} | |
$style_id = $header ? ' ss:StyleID="Header"' : ' ss:StyleID="DataRow"'; | |
$this->write(" <Row" . $style_id. ">\n" . implode("", $tmp) . " </Row>\n"); | |
} | |
function write($str) { | |
if (!$this->headerWritten) { | |
fwrite($this->handle, '<?xml version="1.0"?> | |
<?mso-application progid="Excel.Sheet"?> | |
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" | |
xmlns:o="urn:schemas-microsoft-com:office:office" | |
xmlns:x="urn:schemas-microsoft-com:office:excel" | |
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" | |
xmlns:html="http://www.w3.org/TR/REC-html40"> | |
<o:DocumentProperties> | |
<o:Title>'.htmlspecialchars($this->title).'</o:Title> | |
<o:Author>'.htmlspecialchars($this->author).'</o:Author> | |
</o:DocumentProperties> | |
<Styles> | |
<Style ss:ID="Header"> | |
<Font ss:Bold="1"/> | |
</Style> | |
<Style ss:ID="DataRow"> | |
<Alignment ss:WrapText="1"/> | |
</Style> | |
</Styles> | |
<Worksheet ss:Name="'.htmlspecialchars($this->title).'"> | |
<Table x:FullColumns="1" x:FullRows="1"> | |
'); | |
$this->headerWritten = true; | |
} | |
fwrite($this->handle, $str); | |
} | |
function end() { | |
$this->write(' </Table> | |
</Worksheet> | |
</Workbook> | |
'); | |
fclose($this->handle); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment