Commit 95c167d67377f1aeffcacc43c223ca517066e3bf

Authored by Mihail
1 parent 3c4b566f

add managing with sheets to XlsxParser

vendor/yiisoft/multiparser/CsvParser.php
... ... @@ -141,15 +141,9 @@ class CsvParser extends Parser
141 141 $return[] = $row;
142 142 }
143 143  
144   - $this->closeHandler();
145 144 return $return;
146 145 }
147   -
148   -
149   - protected function closeHandler()
150   - {
151   - $this->file = NULL;
152   - }
  146 +
153 147  
154 148 /**
155 149 * @return array - одномерный массив результата парсинга строки
... ... @@ -167,7 +161,7 @@ class CsvParser extends Parser
167 161 if ($this->hasHeaderRow && $this->keys !== NULL) {
168 162  
169 163 if (count($this->keys) !== count($row)) {
170   - throw new \ErrorException("Ошибка парсинга файла в строке # {$this->current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_line);
  164 + throw new \Exception("Ошибка парсинга файла в строке # {$this->current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_line);
171 165 }
172 166  
173 167 $row = array_combine($this->keys, $row);
... ...
vendor/yiisoft/multiparser/XlsxParser.php
... ... @@ -12,8 +12,29 @@ namespace yii\multiparser;
12 12 use common\components\CustomVarDamp;
13 13  
14 14  
  15 +/**
  16 + * Class XlsxParser
  17 + * @package yii\multiparser
  18 + */
15 19 class XlsxParser extends Parser {
  20 +
  21 + /**
  22 + * @var string - путь куда будут распаковываться файлы, если не указанно - во временный каталог сервера
  23 + */
16 24 public $path_for_extract_files = '';
  25 + /** @var bool
  26 + имеет ли файл заголовок который будет установлен ключами возвращемого массива*/
  27 + public $hasHeaderRow = false;
  28 +
  29 + /**
  30 + * @var int - если указано то считывание будет производиться с этого листа, иначе со всех листов
  31 + * при чтении со всех листов - выходной массив будет иметь номера листов первыми элементами
  32 + */
  33 + public $active_sheet = 0;
  34 +
  35 + protected $strings_arr = [];
  36 + protected $sheets_arr = [];
  37 + protected $result_arr = [];
17 38  
18 39 public function setup()
19 40 {
... ... @@ -26,10 +47,15 @@ class XlsxParser extends Parser {
26 47  
27 48 public function read()
28 49 {
29   - //$this->extractFiles();
30   - CustomVarDamp::dumpAndDie($this->parse());
31 50  
32   - // return $this->parse();
  51 + // $this->extractFiles();
  52 +
  53 + $this->readSheets();
  54 + $this->readStrings();
  55 + $this->readValues();
  56 +
  57 + CustomVarDamp::dumpAndDie($this->result_arr);
  58 + // return $this->$result_arr;
33 59 }
34 60  
35 61 protected function extractFiles ()
... ... @@ -39,43 +65,85 @@ class XlsxParser extends Parser {
39 65 $zip->extractTo( $this->path_for_extract_files );
40 66 $zip->close();
41 67 } else {
42   - throw new \Exception('Ошибка чтения xlsx файла');
  68 + throw new \Exception( 'Ошибка чтения xlsx файла' );
  69 + }
  70 + }
  71 +
  72 + protected function readSheets ()
  73 + {
  74 + if ( $this->active_sheet ) {
  75 + $this->sheets_arr[ $this->active_sheet ] = 'Sheet' . $this->active_sheet;
  76 + return;
  77 + }
  78 +
  79 + $xml = simplexml_load_file( $this->path_for_extract_files . '/xl/workbook.xml' );
  80 + foreach ( $xml->sheets->children() as $sheet ) {
  81 + $sheet_name = '';
  82 + $sheet_id = 0;
  83 + $attr = $sheet->attributes();
  84 + foreach ( $attr as $name => $value ) {
  85 + if ($name == 'name')
  86 + $sheet_name = (string)$value;
  87 +
  88 + if ($name == 'sheetId')
  89 + $sheet_id = $value;
  90 +
  91 + }
  92 + if ( $sheet_name && $sheet_id ) {
  93 + $this->sheets_arr[$sheet_name] = 'Sheet' . $sheet_id;
  94 + }
  95 +//
  96 + }
  97 + }
  98 +
  99 + protected function readStrings ()
  100 + {
  101 + $xml = simplexml_load_file( $this->path_for_extract_files . '/xl/sharedStrings.xml' );
  102 + foreach ( $xml->children() as $item ) {
  103 + $this->strings_arr[] = (string)$item->t;
43 104 }
44 105 }
45 106  
46   - protected function parse ()
  107 + protected function readValues ()
47 108 {
48   - $result = [];
49   - // while ($sheet = @readdir($this->file)) {
50   - foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) {
  109 + //foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) {
  110 + foreach ( $this->sheets_arr as $sheet ) {
51 111 //проходим по всем файлам из директории /xl/worksheets/
52 112 //CustomVarDamp::dumpAndDie($sheet);
53   - if ($sheet != "." && $sheet != ".." && $sheet != '_rels') {
54   - $xml = simplexml_load_file( $sheet );
  113 + $sheet_path = $this->path_for_extract_files . '/xl/worksheets/' . $sheet . '.xml';
  114 + if ( file_exists( $sheet_path ) && is_readable( $sheet_path ) ) {
  115 + $xml = simplexml_load_file( $sheet_path );
55 116 //по каждой строке
56   - $row = 0;
57   -
58   - foreach ( $xml->sheetData->row as $item ) {
59   - $result[$sheet][$row] = array();
60   - //по каждой ячейке строки
61   - $cell = 0;
62   - foreach ( $item as $child ) {
63   - // $attr = $child->attributes();
64   -
65   - if( isset($child->v) ) {
66   - $value = (string)$child->v;
67   - }else{
68   - $value = false;
69   - }
70   -
71   - // $result[$sheet][$row][$cell] = isset($attr['t']) ? $sharedStringsArr[$value] : $value;
72   - $result[$sheet][$row][$cell] = $value;
73   - $cell++;
74   - }
75   - $row++;
  117 + $current_row = 0;
  118 +
  119 + foreach ( $xml->sheetData->row as $row_values ) {
  120 + $this->readRowValues( $row_values, $sheet , $current_row );
  121 + $current_row++;
76 122 }
77 123 }
78 124 }
79   - return $result;
  125 + }
  126 +
  127 + protected function readRowValues ( $item, $sheet , $current_row )
  128 + {
  129 + $this->result_arr[$sheet][$current_row] = array();
  130 + //по каждой ячейке строки
  131 + $cell = 0;
  132 + foreach ( $item as $child ) {
  133 + $attr = $child->attributes();
  134 +
  135 + if( isset($child->v) ) {
  136 + $value = (string)$child->v;
  137 + }else{
  138 + $value = false;
  139 + }
  140 + if ( isset( $attr['t'] ) ) {
  141 + $this->result_arr[$sheet][$current_row][$cell] = $this->strings_arr[ $value ];
  142 + }else{
  143 + $this->result_arr[$sheet][$current_row][$cell] = $value;
  144 + }
  145 + $cell++;
  146 + }
  147 +
80 148 }
81 149 }
82 150 \ No newline at end of file
... ...