Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created December 8, 2014 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/cf9df474662c88ba7951 to your computer and use it in GitHub Desktop.
Save troelskn/cf9df474662c88ba7951 to your computer and use it in GitHub Desktop.
<?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", "&#13;", 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