106 lines
3.1 KiB
PHP
106 lines
3.1 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Документ
|
|
*/
|
|
namespace ctiso\Excel;
|
|
use XMLWriter,
|
|
Exception;
|
|
|
|
class Document {
|
|
static $ns = "urn:schemas-microsoft-com:office:spreadsheet";
|
|
private $table = array ();
|
|
protected $styles = array();
|
|
|
|
function addTable($table) {
|
|
$this->table [] = $table;
|
|
}
|
|
|
|
/**
|
|
* Добавление стиля к документу
|
|
* @param $name string Имя стиля
|
|
* @param $values array Параметры стиля
|
|
* @param $type Тип стиля
|
|
*/
|
|
function setStyle ($name, array $values, $type = 'Interior')
|
|
{
|
|
if(!isset($this->styles[$name])) {
|
|
$this->styles[$name] = [];
|
|
}
|
|
$this->styles[$name][$type] = $values;
|
|
}
|
|
|
|
/**
|
|
* Генерация стилей
|
|
*/
|
|
private function createStyles (XMLWriter $doc) {
|
|
$doc->startElement('Styles');
|
|
foreach ($this->styles as $name => $sn) {
|
|
$doc->startElement('Style');
|
|
$doc->writeAttribute('ss:ID', $name);
|
|
foreach ($sn as $type => $s) {
|
|
// Стиль Borders - составной
|
|
if ($type == 'Borders') {
|
|
$doc->startElement('Borders');
|
|
foreach ($s as $border) {
|
|
$border/*: array*/ = $border;
|
|
$doc->startElement('Border');
|
|
foreach ($border as $key => $value) {
|
|
$doc->writeAttribute('ss:' . $key, $value);
|
|
}
|
|
$doc->endElement();
|
|
}
|
|
$doc->endElement();
|
|
} else {
|
|
$doc->startElement($type);
|
|
foreach ($s as $key => $value) {
|
|
$doc->writeAttribute('ss:' . $key, $value);
|
|
}
|
|
$doc->endElement();
|
|
}
|
|
}
|
|
$doc->endElement();
|
|
}
|
|
$doc->endElement();
|
|
}
|
|
|
|
/**
|
|
* Преобразует переводы строки в спец символы
|
|
*/
|
|
function clean ($s) {
|
|
assert(is_string($s));
|
|
|
|
return strtr($s, ["\n" => " "]);
|
|
}
|
|
|
|
/**
|
|
* Сохраняет таблицу в формате Office 2003 XML
|
|
* http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
|
|
*/
|
|
function save($filename)
|
|
{
|
|
$doc = new XMLWriter();
|
|
if (!$doc->openURI($filename)) {
|
|
throw new Exception("unknown file " . $filename);
|
|
}
|
|
$doc->setIndent(false);
|
|
$doc->startDocument('1.0','utf-8');
|
|
$doc->startElement('Workbook');
|
|
$doc->writeAttribute('xmlns', self::$ns);
|
|
$doc->writeAttribute('xmlns:ss', self::$ns);
|
|
|
|
$this->createStyles($doc);
|
|
|
|
foreach ($this->table as $table) {
|
|
if ($table instanceof Table) {
|
|
$table->createTable($doc);
|
|
} else {
|
|
$table_data = call_user_func($table);
|
|
$table_data->createTable($doc);
|
|
unset($table_data);
|
|
}
|
|
}
|
|
$doc->endElement();
|
|
}
|
|
}
|
|
|