From 95c167d67377f1aeffcacc43c223ca517066e3bf Mon Sep 17 00:00:00 2001 From: Mihail Date: Thu, 22 Oct 2015 14:45:58 +0300 Subject: [PATCH] add managing with sheets to XlsxParser --- vendor/yiisoft/multiparser/CsvParser.php | 10 ++-------- vendor/yiisoft/multiparser/XlsxParser.php | 130 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------- 2 files changed, 101 insertions(+), 39 deletions(-) diff --git a/vendor/yiisoft/multiparser/CsvParser.php b/vendor/yiisoft/multiparser/CsvParser.php index 9c9f29c..81a6ff3 100644 --- a/vendor/yiisoft/multiparser/CsvParser.php +++ b/vendor/yiisoft/multiparser/CsvParser.php @@ -141,15 +141,9 @@ class CsvParser extends Parser $return[] = $row; } - $this->closeHandler(); return $return; } - - - protected function closeHandler() - { - $this->file = NULL; - } + /** * @return array - одномерный массив результата парсинга строки @@ -167,7 +161,7 @@ class CsvParser extends Parser if ($this->hasHeaderRow && $this->keys !== NULL) { if (count($this->keys) !== count($row)) { - throw new \ErrorException("Ошибка парсинга файла в строке # {$this->current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_line); + throw new \Exception("Ошибка парсинга файла в строке # {$this->current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_line); } $row = array_combine($this->keys, $row); diff --git a/vendor/yiisoft/multiparser/XlsxParser.php b/vendor/yiisoft/multiparser/XlsxParser.php index 4c4bc8a..116ac41 100644 --- a/vendor/yiisoft/multiparser/XlsxParser.php +++ b/vendor/yiisoft/multiparser/XlsxParser.php @@ -12,8 +12,29 @@ namespace yii\multiparser; use common\components\CustomVarDamp; +/** + * Class XlsxParser + * @package yii\multiparser + */ class XlsxParser extends Parser { + + /** + * @var string - путь куда будут распаковываться файлы, если не указанно - во временный каталог сервера + */ public $path_for_extract_files = ''; + /** @var bool + имеет ли файл заголовок который будет установлен ключами возвращемого массива*/ + public $hasHeaderRow = false; + + /** + * @var int - если указано то считывание будет производиться с этого листа, иначе со всех листов + * при чтении со всех листов - выходной массив будет иметь номера листов первыми элементами + */ + public $active_sheet = 0; + + protected $strings_arr = []; + protected $sheets_arr = []; + protected $result_arr = []; public function setup() { @@ -26,10 +47,15 @@ class XlsxParser extends Parser { public function read() { - //$this->extractFiles(); - CustomVarDamp::dumpAndDie($this->parse()); - // return $this->parse(); + // $this->extractFiles(); + + $this->readSheets(); + $this->readStrings(); + $this->readValues(); + + CustomVarDamp::dumpAndDie($this->result_arr); + // return $this->$result_arr; } protected function extractFiles () @@ -39,43 +65,85 @@ class XlsxParser extends Parser { $zip->extractTo( $this->path_for_extract_files ); $zip->close(); } else { - throw new \Exception('Ошибка чтения xlsx файла'); + throw new \Exception( 'Ошибка чтения xlsx файла' ); + } + } + + protected function readSheets () + { + if ( $this->active_sheet ) { + $this->sheets_arr[ $this->active_sheet ] = 'Sheet' . $this->active_sheet; + return; + } + + $xml = simplexml_load_file( $this->path_for_extract_files . '/xl/workbook.xml' ); + foreach ( $xml->sheets->children() as $sheet ) { + $sheet_name = ''; + $sheet_id = 0; + $attr = $sheet->attributes(); + foreach ( $attr as $name => $value ) { + if ($name == 'name') + $sheet_name = (string)$value; + + if ($name == 'sheetId') + $sheet_id = $value; + + } + if ( $sheet_name && $sheet_id ) { + $this->sheets_arr[$sheet_name] = 'Sheet' . $sheet_id; + } +// + } + } + + protected function readStrings () + { + $xml = simplexml_load_file( $this->path_for_extract_files . '/xl/sharedStrings.xml' ); + foreach ( $xml->children() as $item ) { + $this->strings_arr[] = (string)$item->t; } } - protected function parse () + protected function readValues () { - $result = []; - // while ($sheet = @readdir($this->file)) { - foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) { + //foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) { + foreach ( $this->sheets_arr as $sheet ) { //проходим по всем файлам из директории /xl/worksheets/ //CustomVarDamp::dumpAndDie($sheet); - if ($sheet != "." && $sheet != ".." && $sheet != '_rels') { - $xml = simplexml_load_file( $sheet ); + $sheet_path = $this->path_for_extract_files . '/xl/worksheets/' . $sheet . '.xml'; + if ( file_exists( $sheet_path ) && is_readable( $sheet_path ) ) { + $xml = simplexml_load_file( $sheet_path ); //по каждой строке - $row = 0; - - foreach ( $xml->sheetData->row as $item ) { - $result[$sheet][$row] = array(); - //по каждой ячейке строки - $cell = 0; - foreach ( $item as $child ) { - // $attr = $child->attributes(); - - if( isset($child->v) ) { - $value = (string)$child->v; - }else{ - $value = false; - } - - // $result[$sheet][$row][$cell] = isset($attr['t']) ? $sharedStringsArr[$value] : $value; - $result[$sheet][$row][$cell] = $value; - $cell++; - } - $row++; + $current_row = 0; + + foreach ( $xml->sheetData->row as $row_values ) { + $this->readRowValues( $row_values, $sheet , $current_row ); + $current_row++; } } } - return $result; + } + + protected function readRowValues ( $item, $sheet , $current_row ) + { + $this->result_arr[$sheet][$current_row] = array(); + //по каждой ячейке строки + $cell = 0; + foreach ( $item as $child ) { + $attr = $child->attributes(); + + if( isset($child->v) ) { + $value = (string)$child->v; + }else{ + $value = false; + } + if ( isset( $attr['t'] ) ) { + $this->result_arr[$sheet][$current_row][$cell] = $this->strings_arr[ $value ]; + }else{ + $this->result_arr[$sheet][$current_row][$cell] = $value; + } + $cell++; + } + } } \ No newline at end of file -- libgit2 0.21.4