Worksheet.php 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Worksheet;
  3. use ArrayObject;
  4. use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
  5. use PhpOffice\PhpSpreadsheet\Cell\Cell;
  6. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  7. use PhpOffice\PhpSpreadsheet\Cell\DataType;
  8. use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
  9. use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
  10. use PhpOffice\PhpSpreadsheet\Chart\Chart;
  11. use PhpOffice\PhpSpreadsheet\Collection\Cells;
  12. use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
  13. use PhpOffice\PhpSpreadsheet\Comment;
  14. use PhpOffice\PhpSpreadsheet\Exception;
  15. use PhpOffice\PhpSpreadsheet\IComparable;
  16. use PhpOffice\PhpSpreadsheet\NamedRange;
  17. use PhpOffice\PhpSpreadsheet\ReferenceHelper;
  18. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  19. use PhpOffice\PhpSpreadsheet\Shared;
  20. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  21. use PhpOffice\PhpSpreadsheet\Style\Color;
  22. use PhpOffice\PhpSpreadsheet\Style\Conditional;
  23. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  24. use PhpOffice\PhpSpreadsheet\Style\Style;
  25. class Worksheet implements IComparable
  26. {
  27. // Break types
  28. const BREAK_NONE = 0;
  29. const BREAK_ROW = 1;
  30. const BREAK_COLUMN = 2;
  31. // Sheet state
  32. const SHEETSTATE_VISIBLE = 'visible';
  33. const SHEETSTATE_HIDDEN = 'hidden';
  34. const SHEETSTATE_VERYHIDDEN = 'veryHidden';
  35. /**
  36. * Invalid characters in sheet title.
  37. *
  38. * @var array
  39. */
  40. private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']'];
  41. /**
  42. * Parent spreadsheet.
  43. *
  44. * @var Spreadsheet
  45. */
  46. private $parent;
  47. /**
  48. * Collection of cells.
  49. *
  50. * @var Cells
  51. */
  52. private $cellCollection;
  53. /**
  54. * Collection of row dimensions.
  55. *
  56. * @var RowDimension[]
  57. */
  58. private $rowDimensions = [];
  59. /**
  60. * Default row dimension.
  61. *
  62. * @var RowDimension
  63. */
  64. private $defaultRowDimension;
  65. /**
  66. * Collection of column dimensions.
  67. *
  68. * @var ColumnDimension[]
  69. */
  70. private $columnDimensions = [];
  71. /**
  72. * Default column dimension.
  73. *
  74. * @var ColumnDimension
  75. */
  76. private $defaultColumnDimension;
  77. /**
  78. * Collection of drawings.
  79. *
  80. * @var BaseDrawing[]
  81. */
  82. private $drawingCollection;
  83. /**
  84. * Collection of Chart objects.
  85. *
  86. * @var Chart[]
  87. */
  88. private $chartCollection = [];
  89. /**
  90. * Worksheet title.
  91. *
  92. * @var string
  93. */
  94. private $title;
  95. /**
  96. * Sheet state.
  97. *
  98. * @var string
  99. */
  100. private $sheetState;
  101. /**
  102. * Page setup.
  103. *
  104. * @var PageSetup
  105. */
  106. private $pageSetup;
  107. /**
  108. * Page margins.
  109. *
  110. * @var PageMargins
  111. */
  112. private $pageMargins;
  113. /**
  114. * Page header/footer.
  115. *
  116. * @var HeaderFooter
  117. */
  118. private $headerFooter;
  119. /**
  120. * Sheet view.
  121. *
  122. * @var SheetView
  123. */
  124. private $sheetView;
  125. /**
  126. * Protection.
  127. *
  128. * @var Protection
  129. */
  130. private $protection;
  131. /**
  132. * Collection of styles.
  133. *
  134. * @var Style[]
  135. */
  136. private $styles = [];
  137. /**
  138. * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
  139. *
  140. * @var array
  141. */
  142. private $conditionalStylesCollection = [];
  143. /**
  144. * Is the current cell collection sorted already?
  145. *
  146. * @var bool
  147. */
  148. private $cellCollectionIsSorted = false;
  149. /**
  150. * Collection of breaks.
  151. *
  152. * @var array
  153. */
  154. private $breaks = [];
  155. /**
  156. * Collection of merged cell ranges.
  157. *
  158. * @var array
  159. */
  160. private $mergeCells = [];
  161. /**
  162. * Collection of protected cell ranges.
  163. *
  164. * @var array
  165. */
  166. private $protectedCells = [];
  167. /**
  168. * Autofilter Range and selection.
  169. *
  170. * @var AutoFilter
  171. */
  172. private $autoFilter;
  173. /**
  174. * Freeze pane.
  175. *
  176. * @var null|string
  177. */
  178. private $freezePane;
  179. /**
  180. * Default position of the right bottom pane.
  181. *
  182. * @var null|string
  183. */
  184. private $topLeftCell;
  185. /**
  186. * Show gridlines?
  187. *
  188. * @var bool
  189. */
  190. private $showGridlines = true;
  191. /**
  192. * Print gridlines?
  193. *
  194. * @var bool
  195. */
  196. private $printGridlines = false;
  197. /**
  198. * Show row and column headers?
  199. *
  200. * @var bool
  201. */
  202. private $showRowColHeaders = true;
  203. /**
  204. * Show summary below? (Row/Column outline).
  205. *
  206. * @var bool
  207. */
  208. private $showSummaryBelow = true;
  209. /**
  210. * Show summary right? (Row/Column outline).
  211. *
  212. * @var bool
  213. */
  214. private $showSummaryRight = true;
  215. /**
  216. * Collection of comments.
  217. *
  218. * @var Comment[]
  219. */
  220. private $comments = [];
  221. /**
  222. * Active cell. (Only one!).
  223. *
  224. * @var string
  225. */
  226. private $activeCell = 'A1';
  227. /**
  228. * Selected cells.
  229. *
  230. * @var string
  231. */
  232. private $selectedCells = 'A1';
  233. /**
  234. * Cached highest column.
  235. *
  236. * @var string
  237. */
  238. private $cachedHighestColumn = 'A';
  239. /**
  240. * Cached highest row.
  241. *
  242. * @var int
  243. */
  244. private $cachedHighestRow = 1;
  245. /**
  246. * Right-to-left?
  247. *
  248. * @var bool
  249. */
  250. private $rightToLeft = false;
  251. /**
  252. * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
  253. *
  254. * @var array
  255. */
  256. private $hyperlinkCollection = [];
  257. /**
  258. * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
  259. *
  260. * @var array
  261. */
  262. private $dataValidationCollection = [];
  263. /**
  264. * Tab color.
  265. *
  266. * @var Color
  267. */
  268. private $tabColor;
  269. /**
  270. * Dirty flag.
  271. *
  272. * @var bool
  273. */
  274. private $dirty = true;
  275. /**
  276. * Hash.
  277. *
  278. * @var string
  279. */
  280. private $hash;
  281. /**
  282. * CodeName.
  283. *
  284. * @var string
  285. */
  286. private $codeName;
  287. /**
  288. * Create a new worksheet.
  289. *
  290. * @param Spreadsheet $parent
  291. * @param string $pTitle
  292. */
  293. public function __construct(Spreadsheet $parent = null, $pTitle = 'Worksheet')
  294. {
  295. // Set parent and title
  296. $this->parent = $parent;
  297. $this->setTitle($pTitle, false);
  298. // setTitle can change $pTitle
  299. $this->setCodeName($this->getTitle());
  300. $this->setSheetState(self::SHEETSTATE_VISIBLE);
  301. $this->cellCollection = CellsFactory::getInstance($this);
  302. // Set page setup
  303. $this->pageSetup = new PageSetup();
  304. // Set page margins
  305. $this->pageMargins = new PageMargins();
  306. // Set page header/footer
  307. $this->headerFooter = new HeaderFooter();
  308. // Set sheet view
  309. $this->sheetView = new SheetView();
  310. // Drawing collection
  311. $this->drawingCollection = new \ArrayObject();
  312. // Chart collection
  313. $this->chartCollection = new \ArrayObject();
  314. // Protection
  315. $this->protection = new Protection();
  316. // Default row dimension
  317. $this->defaultRowDimension = new RowDimension(null);
  318. // Default column dimension
  319. $this->defaultColumnDimension = new ColumnDimension(null);
  320. $this->autoFilter = new AutoFilter(null, $this);
  321. }
  322. /**
  323. * Disconnect all cells from this Worksheet object,
  324. * typically so that the worksheet object can be unset.
  325. */
  326. public function disconnectCells()
  327. {
  328. if ($this->cellCollection !== null) {
  329. $this->cellCollection->unsetWorksheetCells();
  330. $this->cellCollection = null;
  331. }
  332. // detach ourself from the workbook, so that it can then delete this worksheet successfully
  333. $this->parent = null;
  334. }
  335. /**
  336. * Code to execute when this worksheet is unset().
  337. */
  338. public function __destruct()
  339. {
  340. Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
  341. $this->disconnectCells();
  342. }
  343. /**
  344. * Return the cell collection.
  345. *
  346. * @return Cells
  347. */
  348. public function getCellCollection()
  349. {
  350. return $this->cellCollection;
  351. }
  352. /**
  353. * Get array of invalid characters for sheet title.
  354. *
  355. * @return array
  356. */
  357. public static function getInvalidCharacters()
  358. {
  359. return self::$invalidCharacters;
  360. }
  361. /**
  362. * Check sheet code name for valid Excel syntax.
  363. *
  364. * @param string $pValue The string to check
  365. *
  366. * @throws Exception
  367. *
  368. * @return string The valid string
  369. */
  370. private static function checkSheetCodeName($pValue)
  371. {
  372. $CharCount = Shared\StringHelper::countCharacters($pValue);
  373. if ($CharCount == 0) {
  374. throw new Exception('Sheet code name cannot be empty.');
  375. }
  376. // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'"
  377. if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) ||
  378. (Shared\StringHelper::substring($pValue, -1, 1) == '\'') ||
  379. (Shared\StringHelper::substring($pValue, 0, 1) == '\'')) {
  380. throw new Exception('Invalid character found in sheet code name');
  381. }
  382. // Maximum 31 characters allowed for sheet title
  383. if ($CharCount > 31) {
  384. throw new Exception('Maximum 31 characters allowed in sheet code name.');
  385. }
  386. return $pValue;
  387. }
  388. /**
  389. * Check sheet title for valid Excel syntax.
  390. *
  391. * @param string $pValue The string to check
  392. *
  393. * @throws Exception
  394. *
  395. * @return string The valid string
  396. */
  397. private static function checkSheetTitle($pValue)
  398. {
  399. // Some of the printable ASCII characters are invalid: * : / \ ? [ ]
  400. if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) {
  401. throw new Exception('Invalid character found in sheet title');
  402. }
  403. // Maximum 31 characters allowed for sheet title
  404. if (Shared\StringHelper::countCharacters($pValue) > 31) {
  405. throw new Exception('Maximum 31 characters allowed in sheet title.');
  406. }
  407. return $pValue;
  408. }
  409. /**
  410. * Get a sorted list of all cell coordinates currently held in the collection by row and column.
  411. *
  412. * @param bool $sorted Also sort the cell collection?
  413. *
  414. * @return string[]
  415. */
  416. public function getCoordinates($sorted = true)
  417. {
  418. if ($this->cellCollection == null) {
  419. return [];
  420. }
  421. if ($sorted) {
  422. return $this->cellCollection->getSortedCoordinates();
  423. }
  424. return $this->cellCollection->getCoordinates();
  425. }
  426. /**
  427. * Get collection of row dimensions.
  428. *
  429. * @return RowDimension[]
  430. */
  431. public function getRowDimensions()
  432. {
  433. return $this->rowDimensions;
  434. }
  435. /**
  436. * Get default row dimension.
  437. *
  438. * @return RowDimension
  439. */
  440. public function getDefaultRowDimension()
  441. {
  442. return $this->defaultRowDimension;
  443. }
  444. /**
  445. * Get collection of column dimensions.
  446. *
  447. * @return ColumnDimension[]
  448. */
  449. public function getColumnDimensions()
  450. {
  451. return $this->columnDimensions;
  452. }
  453. /**
  454. * Get default column dimension.
  455. *
  456. * @return ColumnDimension
  457. */
  458. public function getDefaultColumnDimension()
  459. {
  460. return $this->defaultColumnDimension;
  461. }
  462. /**
  463. * Get collection of drawings.
  464. *
  465. * @return BaseDrawing[]
  466. */
  467. public function getDrawingCollection()
  468. {
  469. return $this->drawingCollection;
  470. }
  471. /**
  472. * Get collection of charts.
  473. *
  474. * @return Chart[]
  475. */
  476. public function getChartCollection()
  477. {
  478. return $this->chartCollection;
  479. }
  480. /**
  481. * Add chart.
  482. *
  483. * @param Chart $pChart
  484. * @param null|int $iChartIndex Index where chart should go (0,1,..., or null for last)
  485. *
  486. * @return Chart
  487. */
  488. public function addChart(Chart $pChart, $iChartIndex = null)
  489. {
  490. $pChart->setWorksheet($this);
  491. if ($iChartIndex === null) {
  492. $this->chartCollection[] = $pChart;
  493. } else {
  494. // Insert the chart at the requested index
  495. array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]);
  496. }
  497. return $pChart;
  498. }
  499. /**
  500. * Return the count of charts on this worksheet.
  501. *
  502. * @return int The number of charts
  503. */
  504. public function getChartCount()
  505. {
  506. return count($this->chartCollection);
  507. }
  508. /**
  509. * Get a chart by its index position.
  510. *
  511. * @param string $index Chart index position
  512. *
  513. * @return Chart|false
  514. */
  515. public function getChartByIndex($index)
  516. {
  517. $chartCount = count($this->chartCollection);
  518. if ($chartCount == 0) {
  519. return false;
  520. }
  521. if ($index === null) {
  522. $index = --$chartCount;
  523. }
  524. if (!isset($this->chartCollection[$index])) {
  525. return false;
  526. }
  527. return $this->chartCollection[$index];
  528. }
  529. /**
  530. * Return an array of the names of charts on this worksheet.
  531. *
  532. * @return string[] The names of charts
  533. */
  534. public function getChartNames()
  535. {
  536. $chartNames = [];
  537. foreach ($this->chartCollection as $chart) {
  538. $chartNames[] = $chart->getName();
  539. }
  540. return $chartNames;
  541. }
  542. /**
  543. * Get a chart by name.
  544. *
  545. * @param string $chartName Chart name
  546. *
  547. * @return Chart|false
  548. */
  549. public function getChartByName($chartName)
  550. {
  551. $chartCount = count($this->chartCollection);
  552. if ($chartCount == 0) {
  553. return false;
  554. }
  555. foreach ($this->chartCollection as $index => $chart) {
  556. if ($chart->getName() == $chartName) {
  557. return $this->chartCollection[$index];
  558. }
  559. }
  560. return false;
  561. }
  562. /**
  563. * Refresh column dimensions.
  564. *
  565. * @return Worksheet
  566. */
  567. public function refreshColumnDimensions()
  568. {
  569. $currentColumnDimensions = $this->getColumnDimensions();
  570. $newColumnDimensions = [];
  571. foreach ($currentColumnDimensions as $objColumnDimension) {
  572. $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
  573. }
  574. $this->columnDimensions = $newColumnDimensions;
  575. return $this;
  576. }
  577. /**
  578. * Refresh row dimensions.
  579. *
  580. * @return Worksheet
  581. */
  582. public function refreshRowDimensions()
  583. {
  584. $currentRowDimensions = $this->getRowDimensions();
  585. $newRowDimensions = [];
  586. foreach ($currentRowDimensions as $objRowDimension) {
  587. $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
  588. }
  589. $this->rowDimensions = $newRowDimensions;
  590. return $this;
  591. }
  592. /**
  593. * Calculate worksheet dimension.
  594. *
  595. * @return string String containing the dimension of this worksheet
  596. */
  597. public function calculateWorksheetDimension()
  598. {
  599. // Return
  600. return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow();
  601. }
  602. /**
  603. * Calculate worksheet data dimension.
  604. *
  605. * @return string String containing the dimension of this worksheet that actually contain data
  606. */
  607. public function calculateWorksheetDataDimension()
  608. {
  609. // Return
  610. return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow();
  611. }
  612. /**
  613. * Calculate widths for auto-size columns.
  614. *
  615. * @return Worksheet;
  616. */
  617. public function calculateColumnWidths()
  618. {
  619. // initialize $autoSizes array
  620. $autoSizes = [];
  621. foreach ($this->getColumnDimensions() as $colDimension) {
  622. if ($colDimension->getAutoSize()) {
  623. $autoSizes[$colDimension->getColumnIndex()] = -1;
  624. }
  625. }
  626. // There is only something to do if there are some auto-size columns
  627. if (!empty($autoSizes)) {
  628. // build list of cells references that participate in a merge
  629. $isMergeCell = [];
  630. foreach ($this->getMergeCells() as $cells) {
  631. foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
  632. $isMergeCell[$cellReference] = true;
  633. }
  634. }
  635. // loop through all cells in the worksheet
  636. foreach ($this->getCoordinates(false) as $coordinate) {
  637. $cell = $this->getCell($coordinate, false);
  638. if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
  639. //Determine if cell is in merge range
  640. $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
  641. //By default merged cells should be ignored
  642. $isMergedButProceed = false;
  643. //The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide)
  644. if ($isMerged && $cell->isMergeRangeValueCell()) {
  645. $range = $cell->getMergeRange();
  646. $rangeBoundaries = Coordinate::rangeDimension($range);
  647. if ($rangeBoundaries[0] == 1) {
  648. $isMergedButProceed = true;
  649. }
  650. }
  651. // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range
  652. if (!$isMerged || $isMergedButProceed) {
  653. // Calculated value
  654. // To formatted string
  655. $cellValue = NumberFormat::toFormattedString(
  656. $cell->getCalculatedValue(),
  657. $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
  658. );
  659. $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
  660. (float) $autoSizes[$this->cellCollection->getCurrentColumn()],
  661. (float) Shared\Font::calculateColumnWidth(
  662. $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
  663. $cellValue,
  664. $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
  665. $this->getParent()->getDefaultStyle()->getFont()
  666. )
  667. );
  668. }
  669. }
  670. }
  671. // adjust column widths
  672. foreach ($autoSizes as $columnIndex => $width) {
  673. if ($width == -1) {
  674. $width = $this->getDefaultColumnDimension()->getWidth();
  675. }
  676. $this->getColumnDimension($columnIndex)->setWidth($width);
  677. }
  678. }
  679. return $this;
  680. }
  681. /**
  682. * Get parent.
  683. *
  684. * @return Spreadsheet
  685. */
  686. public function getParent()
  687. {
  688. return $this->parent;
  689. }
  690. /**
  691. * Re-bind parent.
  692. *
  693. * @param Spreadsheet $parent
  694. *
  695. * @return Worksheet
  696. */
  697. public function rebindParent(Spreadsheet $parent)
  698. {
  699. if ($this->parent !== null) {
  700. $namedRanges = $this->parent->getNamedRanges();
  701. foreach ($namedRanges as $namedRange) {
  702. $parent->addNamedRange($namedRange);
  703. }
  704. $this->parent->removeSheetByIndex(
  705. $this->parent->getIndex($this)
  706. );
  707. }
  708. $this->parent = $parent;
  709. return $this;
  710. }
  711. /**
  712. * Get title.
  713. *
  714. * @return string
  715. */
  716. public function getTitle()
  717. {
  718. return $this->title;
  719. }
  720. /**
  721. * Set title.
  722. *
  723. * @param string $pValue String containing the dimension of this worksheet
  724. * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
  725. * be updated to reflect the new sheet name.
  726. * This should be left as the default true, unless you are
  727. * certain that no formula cells on any worksheet contain
  728. * references to this worksheet
  729. * @param bool $validate False to skip validation of new title. WARNING: This should only be set
  730. * at parse time (by Readers), where titles can be assumed to be valid.
  731. *
  732. * @return Worksheet
  733. */
  734. public function setTitle($pValue, $updateFormulaCellReferences = true, $validate = true)
  735. {
  736. // Is this a 'rename' or not?
  737. if ($this->getTitle() == $pValue) {
  738. return $this;
  739. }
  740. // Old title
  741. $oldTitle = $this->getTitle();
  742. if ($validate) {
  743. // Syntax check
  744. self::checkSheetTitle($pValue);
  745. if ($this->parent) {
  746. // Is there already such sheet name?
  747. if ($this->parent->sheetNameExists($pValue)) {
  748. // Use name, but append with lowest possible integer
  749. if (Shared\StringHelper::countCharacters($pValue) > 29) {
  750. $pValue = Shared\StringHelper::substring($pValue, 0, 29);
  751. }
  752. $i = 1;
  753. while ($this->parent->sheetNameExists($pValue . ' ' . $i)) {
  754. ++$i;
  755. if ($i == 10) {
  756. if (Shared\StringHelper::countCharacters($pValue) > 28) {
  757. $pValue = Shared\StringHelper::substring($pValue, 0, 28);
  758. }
  759. } elseif ($i == 100) {
  760. if (Shared\StringHelper::countCharacters($pValue) > 27) {
  761. $pValue = Shared\StringHelper::substring($pValue, 0, 27);
  762. }
  763. }
  764. }
  765. $pValue .= " $i";
  766. }
  767. }
  768. }
  769. // Set title
  770. $this->title = $pValue;
  771. $this->dirty = true;
  772. if ($this->parent && $this->parent->getCalculationEngine()) {
  773. // New title
  774. $newTitle = $this->getTitle();
  775. $this->parent->getCalculationEngine()
  776. ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
  777. if ($updateFormulaCellReferences) {
  778. ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle);
  779. }
  780. }
  781. return $this;
  782. }
  783. /**
  784. * Get sheet state.
  785. *
  786. * @return string Sheet state (visible, hidden, veryHidden)
  787. */
  788. public function getSheetState()
  789. {
  790. return $this->sheetState;
  791. }
  792. /**
  793. * Set sheet state.
  794. *
  795. * @param string $value Sheet state (visible, hidden, veryHidden)
  796. *
  797. * @return Worksheet
  798. */
  799. public function setSheetState($value)
  800. {
  801. $this->sheetState = $value;
  802. return $this;
  803. }
  804. /**
  805. * Get page setup.
  806. *
  807. * @return PageSetup
  808. */
  809. public function getPageSetup()
  810. {
  811. return $this->pageSetup;
  812. }
  813. /**
  814. * Set page setup.
  815. *
  816. * @param PageSetup $pValue
  817. *
  818. * @return Worksheet
  819. */
  820. public function setPageSetup(PageSetup $pValue)
  821. {
  822. $this->pageSetup = $pValue;
  823. return $this;
  824. }
  825. /**
  826. * Get page margins.
  827. *
  828. * @return PageMargins
  829. */
  830. public function getPageMargins()
  831. {
  832. return $this->pageMargins;
  833. }
  834. /**
  835. * Set page margins.
  836. *
  837. * @param PageMargins $pValue
  838. *
  839. * @return Worksheet
  840. */
  841. public function setPageMargins(PageMargins $pValue)
  842. {
  843. $this->pageMargins = $pValue;
  844. return $this;
  845. }
  846. /**
  847. * Get page header/footer.
  848. *
  849. * @return HeaderFooter
  850. */
  851. public function getHeaderFooter()
  852. {
  853. return $this->headerFooter;
  854. }
  855. /**
  856. * Set page header/footer.
  857. *
  858. * @param HeaderFooter $pValue
  859. *
  860. * @return Worksheet
  861. */
  862. public function setHeaderFooter(HeaderFooter $pValue)
  863. {
  864. $this->headerFooter = $pValue;
  865. return $this;
  866. }
  867. /**
  868. * Get sheet view.
  869. *
  870. * @return SheetView
  871. */
  872. public function getSheetView()
  873. {
  874. return $this->sheetView;
  875. }
  876. /**
  877. * Set sheet view.
  878. *
  879. * @param SheetView $pValue
  880. *
  881. * @return Worksheet
  882. */
  883. public function setSheetView(SheetView $pValue)
  884. {
  885. $this->sheetView = $pValue;
  886. return $this;
  887. }
  888. /**
  889. * Get Protection.
  890. *
  891. * @return Protection
  892. */
  893. public function getProtection()
  894. {
  895. return $this->protection;
  896. }
  897. /**
  898. * Set Protection.
  899. *
  900. * @param Protection $pValue
  901. *
  902. * @return Worksheet
  903. */
  904. public function setProtection(Protection $pValue)
  905. {
  906. $this->protection = $pValue;
  907. $this->dirty = true;
  908. return $this;
  909. }
  910. /**
  911. * Get highest worksheet column.
  912. *
  913. * @param string $row Return the data highest column for the specified row,
  914. * or the highest column of any row if no row number is passed
  915. *
  916. * @return string Highest column name
  917. */
  918. public function getHighestColumn($row = null)
  919. {
  920. if ($row == null) {
  921. return $this->cachedHighestColumn;
  922. }
  923. return $this->getHighestDataColumn($row);
  924. }
  925. /**
  926. * Get highest worksheet column that contains data.
  927. *
  928. * @param string $row Return the highest data column for the specified row,
  929. * or the highest data column of any row if no row number is passed
  930. *
  931. * @return string Highest column name that contains data
  932. */
  933. public function getHighestDataColumn($row = null)
  934. {
  935. return $this->cellCollection->getHighestColumn($row);
  936. }
  937. /**
  938. * Get highest worksheet row.
  939. *
  940. * @param string $column Return the highest data row for the specified column,
  941. * or the highest row of any column if no column letter is passed
  942. *
  943. * @return int Highest row number
  944. */
  945. public function getHighestRow($column = null)
  946. {
  947. if ($column == null) {
  948. return $this->cachedHighestRow;
  949. }
  950. return $this->getHighestDataRow($column);
  951. }
  952. /**
  953. * Get highest worksheet row that contains data.
  954. *
  955. * @param string $column Return the highest data row for the specified column,
  956. * or the highest data row of any column if no column letter is passed
  957. *
  958. * @return string Highest row number that contains data
  959. */
  960. public function getHighestDataRow($column = null)
  961. {
  962. return $this->cellCollection->getHighestRow($column);
  963. }
  964. /**
  965. * Get highest worksheet column and highest row that have cell records.
  966. *
  967. * @return array Highest column name and highest row number
  968. */
  969. public function getHighestRowAndColumn()
  970. {
  971. return $this->cellCollection->getHighestRowAndColumn();
  972. }
  973. /**
  974. * Set a cell value.
  975. *
  976. * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
  977. * @param mixed $pValue Value of the cell
  978. *
  979. * @return Worksheet
  980. */
  981. public function setCellValue($pCoordinate, $pValue)
  982. {
  983. $this->getCell($pCoordinate)->setValue($pValue);
  984. return $this;
  985. }
  986. /**
  987. * Set a cell value by using numeric cell coordinates.
  988. *
  989. * @param int $columnIndex Numeric column coordinate of the cell
  990. * @param int $row Numeric row coordinate of the cell
  991. * @param mixed $value Value of the cell
  992. *
  993. * @return Worksheet
  994. */
  995. public function setCellValueByColumnAndRow($columnIndex, $row, $value)
  996. {
  997. $this->getCellByColumnAndRow($columnIndex, $row)->setValue($value);
  998. return $this;
  999. }
  1000. /**
  1001. * Set a cell value.
  1002. *
  1003. * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
  1004. * @param mixed $pValue Value of the cell
  1005. * @param string $pDataType Explicit data type, see DataType::TYPE_*
  1006. *
  1007. * @return Worksheet
  1008. */
  1009. public function setCellValueExplicit($pCoordinate, $pValue, $pDataType)
  1010. {
  1011. // Set value
  1012. $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
  1013. return $this;
  1014. }
  1015. /**
  1016. * Set a cell value by using numeric cell coordinates.
  1017. *
  1018. * @param int $columnIndex Numeric column coordinate of the cell
  1019. * @param int $row Numeric row coordinate of the cell
  1020. * @param mixed $value Value of the cell
  1021. * @param string $dataType Explicit data type, see DataType::TYPE_*
  1022. *
  1023. * @return Worksheet
  1024. */
  1025. public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType)
  1026. {
  1027. $this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType);
  1028. return $this;
  1029. }
  1030. /**
  1031. * Get cell at a specific coordinate.
  1032. *
  1033. * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
  1034. * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
  1035. * already exist, or a null should be returned instead
  1036. *
  1037. * @throws Exception
  1038. *
  1039. * @return null|Cell Cell that was found/created or null
  1040. */
  1041. public function getCell($pCoordinate, $createIfNotExists = true)
  1042. {
  1043. // Check cell collection
  1044. if ($this->cellCollection->has(strtoupper($pCoordinate))) {
  1045. return $this->cellCollection->get($pCoordinate);
  1046. }
  1047. // Worksheet reference?
  1048. if (strpos($pCoordinate, '!') !== false) {
  1049. $worksheetReference = self::extractSheetTitle($pCoordinate, true);
  1050. return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists);
  1051. }
  1052. // Named range?
  1053. if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) &&
  1054. (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) {
  1055. $namedRange = NamedRange::resolveRange($pCoordinate, $this);
  1056. if ($namedRange !== null) {
  1057. $pCoordinate = $namedRange->getRange();
  1058. return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists);
  1059. }
  1060. }
  1061. // Uppercase coordinate
  1062. $pCoordinate = strtoupper($pCoordinate);
  1063. if (Coordinate::coordinateIsRange($pCoordinate)) {
  1064. throw new Exception('Cell coordinate can not be a range of cells.');
  1065. } elseif (strpos($pCoordinate, '$') !== false) {
  1066. throw new Exception('Cell coordinate must not be absolute.');
  1067. }
  1068. // Create new cell object, if required
  1069. return $createIfNotExists ? $this->createNewCell($pCoordinate) : null;
  1070. }
  1071. /**
  1072. * Get cell at a specific coordinate by using numeric cell coordinates.
  1073. *
  1074. * @param int $columnIndex Numeric column coordinate of the cell
  1075. * @param int $row Numeric row coordinate of the cell
  1076. * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
  1077. * already exist, or a null should be returned instead
  1078. *
  1079. * @return null|Cell Cell that was found/created or null
  1080. */
  1081. public function getCellByColumnAndRow($columnIndex, $row, $createIfNotExists = true)
  1082. {
  1083. $columnLetter = Coordinate::stringFromColumnIndex($columnIndex);
  1084. $coordinate = $columnLetter . $row;
  1085. if ($this->cellCollection->has($coordinate)) {
  1086. return $this->cellCollection->get($coordinate);
  1087. }
  1088. // Create new cell object, if required
  1089. return $createIfNotExists ? $this->createNewCell($coordinate) : null;
  1090. }
  1091. /**
  1092. * Create a new cell at the specified coordinate.
  1093. *
  1094. * @param string $pCoordinate Coordinate of the cell
  1095. *
  1096. * @return Cell Cell that was created
  1097. */
  1098. private function createNewCell($pCoordinate)
  1099. {
  1100. $cell = new Cell(null, DataType::TYPE_NULL, $this);
  1101. $this->cellCollection->add($pCoordinate, $cell);
  1102. $this->cellCollectionIsSorted = false;
  1103. // Coordinates
  1104. $aCoordinates = Coordinate::coordinateFromString($pCoordinate);
  1105. if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($aCoordinates[0])) {
  1106. $this->cachedHighestColumn = $aCoordinates[0];
  1107. }
  1108. $this->cachedHighestRow = max($this->cachedHighestRow, $aCoordinates[1]);
  1109. // Cell needs appropriate xfIndex from dimensions records
  1110. // but don't create dimension records if they don't already exist
  1111. $rowDimension = $this->getRowDimension($aCoordinates[1], false);
  1112. $columnDimension = $this->getColumnDimension($aCoordinates[0], false);
  1113. if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
  1114. // then there is a row dimension with explicit style, assign it to the cell
  1115. $cell->setXfIndex($rowDimension->getXfIndex());
  1116. } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) {
  1117. // then there is a column dimension, assign it to the cell
  1118. $cell->setXfIndex($columnDimension->getXfIndex());
  1119. }
  1120. return $cell;
  1121. }
  1122. /**
  1123. * Does the cell at a specific coordinate exist?
  1124. *
  1125. * @param string $pCoordinate Coordinate of the cell eg: 'A1'
  1126. *
  1127. * @throws Exception
  1128. *
  1129. * @return bool
  1130. */
  1131. public function cellExists($pCoordinate)
  1132. {
  1133. // Worksheet reference?
  1134. if (strpos($pCoordinate, '!') !== false) {
  1135. $worksheetReference = self::extractSheetTitle($pCoordinate, true);
  1136. return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1]));
  1137. }
  1138. // Named range?
  1139. if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) &&
  1140. (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) {
  1141. $namedRange = NamedRange::resolveRange($pCoordinate, $this);
  1142. if ($namedRange !== null) {
  1143. $pCoordinate = $namedRange->getRange();
  1144. if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {
  1145. if (!$namedRange->getLocalOnly()) {
  1146. return $namedRange->getWorksheet()->cellExists($pCoordinate);
  1147. }
  1148. throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());
  1149. }
  1150. } else {
  1151. return false;
  1152. }
  1153. }
  1154. // Uppercase coordinate
  1155. $pCoordinate = strtoupper($pCoordinate);
  1156. if (Coordinate::coordinateIsRange($pCoordinate)) {
  1157. throw new Exception('Cell coordinate can not be a range of cells.');
  1158. } elseif (strpos($pCoordinate, '$') !== false) {
  1159. throw new Exception('Cell coordinate must not be absolute.');
  1160. }
  1161. // Cell exists?
  1162. return $this->cellCollection->has($pCoordinate);
  1163. }
  1164. /**
  1165. * Cell at a specific coordinate by using numeric cell coordinates exists?
  1166. *
  1167. * @param int $columnIndex Numeric column coordinate of the cell
  1168. * @param int $row Numeric row coordinate of the cell
  1169. *
  1170. * @return bool
  1171. */
  1172. public function cellExistsByColumnAndRow($columnIndex, $row)
  1173. {
  1174. return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row);
  1175. }
  1176. /**
  1177. * Get row dimension at a specific row.
  1178. *
  1179. * @param int $pRow Numeric index of the row
  1180. * @param bool $create
  1181. *
  1182. * @return RowDimension
  1183. */
  1184. public function getRowDimension($pRow, $create = true)
  1185. {
  1186. // Found
  1187. $found = null;
  1188. // Get row dimension
  1189. if (!isset($this->rowDimensions[$pRow])) {
  1190. if (!$create) {
  1191. return null;
  1192. }
  1193. $this->rowDimensions[$pRow] = new RowDimension($pRow);
  1194. $this->cachedHighestRow = max($this->cachedHighestRow, $pRow);
  1195. }
  1196. return $this->rowDimensions[$pRow];
  1197. }
  1198. /**
  1199. * Get column dimension at a specific column.
  1200. *
  1201. * @param string $pColumn String index of the column eg: 'A'
  1202. * @param bool $create
  1203. *
  1204. * @return ColumnDimension
  1205. */
  1206. public function getColumnDimension($pColumn, $create = true)
  1207. {
  1208. // Uppercase coordinate
  1209. $pColumn = strtoupper($pColumn);
  1210. // Fetch dimensions
  1211. if (!isset($this->columnDimensions[$pColumn])) {
  1212. if (!$create) {
  1213. return null;
  1214. }
  1215. $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn);
  1216. if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($pColumn)) {
  1217. $this->cachedHighestColumn = $pColumn;
  1218. }
  1219. }
  1220. return $this->columnDimensions[$pColumn];
  1221. }
  1222. /**
  1223. * Get column dimension at a specific column by using numeric cell coordinates.
  1224. *
  1225. * @param int $columnIndex Numeric column coordinate of the cell
  1226. *
  1227. * @return ColumnDimension
  1228. */
  1229. public function getColumnDimensionByColumn($columnIndex)
  1230. {
  1231. return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
  1232. }
  1233. /**
  1234. * Get styles.
  1235. *
  1236. * @return Style[]
  1237. */
  1238. public function getStyles()
  1239. {
  1240. return $this->styles;
  1241. }
  1242. /**
  1243. * Get style for cell.
  1244. *
  1245. * @param string $pCellCoordinate Cell coordinate (or range) to get style for, eg: 'A1'
  1246. *
  1247. * @throws Exception
  1248. *
  1249. * @return Style
  1250. */
  1251. public function getStyle($pCellCoordinate)
  1252. {
  1253. // set this sheet as active
  1254. $this->parent->setActiveSheetIndex($this->parent->getIndex($this));
  1255. // set cell coordinate as active
  1256. $this->setSelectedCells(strtoupper($pCellCoordinate));
  1257. return $this->parent->getCellXfSupervisor();
  1258. }
  1259. /**
  1260. * Get conditional styles for a cell.
  1261. *
  1262. * @param string $pCoordinate eg: 'A1'
  1263. *
  1264. * @return Conditional[]
  1265. */
  1266. public function getConditionalStyles($pCoordinate)
  1267. {
  1268. $pCoordinate = strtoupper($pCoordinate);
  1269. if (!isset($this->conditionalStylesCollection[$pCoordinate])) {
  1270. $this->conditionalStylesCollection[$pCoordinate] = [];
  1271. }
  1272. return $this->conditionalStylesCollection[$pCoordinate];
  1273. }
  1274. /**
  1275. * Do conditional styles exist for this cell?
  1276. *
  1277. * @param string $pCoordinate eg: 'A1'
  1278. *
  1279. * @return bool
  1280. */
  1281. public function conditionalStylesExists($pCoordinate)
  1282. {
  1283. return isset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
  1284. }
  1285. /**
  1286. * Removes conditional styles for a cell.
  1287. *
  1288. * @param string $pCoordinate eg: 'A1'
  1289. *
  1290. * @return Worksheet
  1291. */
  1292. public function removeConditionalStyles($pCoordinate)
  1293. {
  1294. unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
  1295. return $this;
  1296. }
  1297. /**
  1298. * Get collection of conditional styles.
  1299. *
  1300. * @return array
  1301. */
  1302. public function getConditionalStylesCollection()
  1303. {
  1304. return $this->conditionalStylesCollection;
  1305. }
  1306. /**
  1307. * Set conditional styles.
  1308. *
  1309. * @param string $pCoordinate eg: 'A1'
  1310. * @param $pValue Conditional[]
  1311. *
  1312. * @return Worksheet
  1313. */
  1314. public function setConditionalStyles($pCoordinate, $pValue)
  1315. {
  1316. $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue;
  1317. return $this;
  1318. }
  1319. /**
  1320. * Get style for cell by using numeric cell coordinates.
  1321. *
  1322. * @param int $columnIndex1 Numeric column coordinate of the cell
  1323. * @param int $row1 Numeric row coordinate of the cell
  1324. * @param null|int $columnIndex2 Numeric column coordinate of the range cell
  1325. * @param null|int $row2 Numeric row coordinate of the range cell
  1326. *
  1327. * @return Style
  1328. */
  1329. public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null)
  1330. {
  1331. if ($columnIndex2 !== null && $row2 !== null) {
  1332. $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
  1333. return $this->getStyle($cellRange);
  1334. }
  1335. return $this->getStyle(Coordinate::stringFromColumnIndex($columnIndex1) . $row1);
  1336. }
  1337. /**
  1338. * Duplicate cell style to a range of cells.
  1339. *
  1340. * Please note that this will overwrite existing cell styles for cells in range!
  1341. *
  1342. * @param Style $pCellStyle Cell style to duplicate
  1343. * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
  1344. *
  1345. * @throws Exception
  1346. *
  1347. * @return Worksheet
  1348. */
  1349. public function duplicateStyle(Style $pCellStyle, $pRange)
  1350. {
  1351. // Add the style to the workbook if necessary
  1352. $workbook = $this->parent;
  1353. if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
  1354. // there is already such cell Xf in our collection
  1355. $xfIndex = $existingStyle->getIndex();
  1356. } else {
  1357. // we don't have such a cell Xf, need to add
  1358. $workbook->addCellXf($pCellStyle);
  1359. $xfIndex = $pCellStyle->getIndex();
  1360. }
  1361. // Calculate range outer borders
  1362. list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
  1363. // Make sure we can loop upwards on rows and columns
  1364. if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
  1365. $tmp = $rangeStart;
  1366. $rangeStart = $rangeEnd;
  1367. $rangeEnd = $tmp;
  1368. }
  1369. // Loop through cells and apply styles
  1370. for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
  1371. for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
  1372. $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
  1373. }
  1374. }
  1375. return $this;
  1376. }
  1377. /**
  1378. * Duplicate conditional style to a range of cells.
  1379. *
  1380. * Please note that this will overwrite existing cell styles for cells in range!
  1381. *
  1382. * @param Conditional[] $pCellStyle Cell style to duplicate
  1383. * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
  1384. *
  1385. * @throws Exception
  1386. *
  1387. * @return Worksheet
  1388. */
  1389. public function duplicateConditionalStyle(array $pCellStyle, $pRange = '')
  1390. {
  1391. foreach ($pCellStyle as $cellStyle) {
  1392. if (!($cellStyle instanceof Conditional)) {
  1393. throw new Exception('Style is not a conditional style');
  1394. }
  1395. }
  1396. // Calculate range outer borders
  1397. list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
  1398. // Make sure we can loop upwards on rows and columns
  1399. if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
  1400. $tmp = $rangeStart;
  1401. $rangeStart = $rangeEnd;
  1402. $rangeEnd = $tmp;
  1403. }
  1404. // Loop through cells and apply styles
  1405. for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
  1406. for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
  1407. $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $pCellStyle);
  1408. }
  1409. }
  1410. return $this;
  1411. }
  1412. /**
  1413. * Set break on a cell.
  1414. *
  1415. * @param string $pCoordinate Cell coordinate (e.g. A1)
  1416. * @param int $pBreak Break type (type of Worksheet::BREAK_*)
  1417. *
  1418. * @throws Exception
  1419. *
  1420. * @return Worksheet
  1421. */
  1422. public function setBreak($pCoordinate, $pBreak)
  1423. {
  1424. // Uppercase coordinate
  1425. $pCoordinate = strtoupper($pCoordinate);
  1426. if ($pCoordinate != '') {
  1427. if ($pBreak == self::BREAK_NONE) {
  1428. if (isset($this->breaks[$pCoordinate])) {
  1429. unset($this->breaks[$pCoordinate]);
  1430. }
  1431. } else {
  1432. $this->breaks[$pCoordinate] = $pBreak;
  1433. }
  1434. } else {
  1435. throw new Exception('No cell coordinate specified.');
  1436. }
  1437. return $this;
  1438. }
  1439. /**
  1440. * Set break on a cell by using numeric cell coordinates.
  1441. *
  1442. * @param int $columnIndex Numeric column coordinate of the cell
  1443. * @param int $row Numeric row coordinate of the cell
  1444. * @param int $break Break type (type of Worksheet::BREAK_*)
  1445. *
  1446. * @return Worksheet
  1447. */
  1448. public function setBreakByColumnAndRow($columnIndex, $row, $break)
  1449. {
  1450. return $this->setBreak(Coordinate::stringFromColumnIndex($columnIndex) . $row, $break);
  1451. }
  1452. /**
  1453. * Get breaks.
  1454. *
  1455. * @return array[]
  1456. */
  1457. public function getBreaks()
  1458. {
  1459. return $this->breaks;
  1460. }
  1461. /**
  1462. * Set merge on a cell range.
  1463. *
  1464. * @param string $pRange Cell range (e.g. A1:E1)
  1465. *
  1466. * @throws Exception
  1467. *
  1468. * @return Worksheet
  1469. */
  1470. public function mergeCells($pRange)
  1471. {
  1472. // Uppercase coordinate
  1473. $pRange = strtoupper($pRange);
  1474. if (strpos($pRange, ':') !== false) {
  1475. $this->mergeCells[$pRange] = $pRange;
  1476. // make sure cells are created
  1477. // get the cells in the range
  1478. $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
  1479. // create upper left cell if it does not already exist
  1480. $upperLeft = $aReferences[0];
  1481. if (!$this->cellExists($upperLeft)) {
  1482. $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
  1483. }
  1484. // Blank out the rest of the cells in the range (if they exist)
  1485. $count = count($aReferences);
  1486. for ($i = 1; $i < $count; ++$i) {
  1487. if ($this->cellExists($aReferences[$i])) {
  1488. $this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL);
  1489. }
  1490. }
  1491. } else {
  1492. throw new Exception('Merge must be set on a range of cells.');
  1493. }
  1494. return $this;
  1495. }
  1496. /**
  1497. * Set merge on a cell range by using numeric cell coordinates.
  1498. *
  1499. * @param int $columnIndex1 Numeric column coordinate of the first cell
  1500. * @param int $row1 Numeric row coordinate of the first cell
  1501. * @param int $columnIndex2 Numeric column coordinate of the last cell
  1502. * @param int $row2 Numeric row coordinate of the last cell
  1503. *
  1504. * @throws Exception
  1505. *
  1506. * @return Worksheet
  1507. */
  1508. public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
  1509. {
  1510. $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
  1511. return $this->mergeCells($cellRange);
  1512. }
  1513. /**
  1514. * Remove merge on a cell range.
  1515. *
  1516. * @param string $pRange Cell range (e.g. A1:E1)
  1517. *
  1518. * @throws Exception
  1519. *
  1520. * @return Worksheet
  1521. */
  1522. public function unmergeCells($pRange)
  1523. {
  1524. // Uppercase coordinate
  1525. $pRange = strtoupper($pRange);
  1526. if (strpos($pRange, ':') !== false) {
  1527. if (isset($this->mergeCells[$pRange])) {
  1528. unset($this->mergeCells[$pRange]);
  1529. } else {
  1530. throw new Exception('Cell range ' . $pRange . ' not known as merged.');
  1531. }
  1532. } else {
  1533. throw new Exception('Merge can only be removed from a range of cells.');
  1534. }
  1535. return $this;
  1536. }
  1537. /**
  1538. * Remove merge on a cell range by using numeric cell coordinates.
  1539. *
  1540. * @param int $columnIndex1 Numeric column coordinate of the first cell
  1541. * @param int $row1 Numeric row coordinate of the first cell
  1542. * @param int $columnIndex2 Numeric column coordinate of the last cell
  1543. * @param int $row2 Numeric row coordinate of the last cell
  1544. *
  1545. * @throws Exception
  1546. *
  1547. * @return Worksheet
  1548. */
  1549. public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
  1550. {
  1551. $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
  1552. return $this->unmergeCells($cellRange);
  1553. }
  1554. /**
  1555. * Get merge cells array.
  1556. *
  1557. * @return array[]
  1558. */
  1559. public function getMergeCells()
  1560. {
  1561. return $this->mergeCells;
  1562. }
  1563. /**
  1564. * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
  1565. * a single cell range.
  1566. *
  1567. * @param array $pValue
  1568. *
  1569. * @return Worksheet
  1570. */
  1571. public function setMergeCells(array $pValue)
  1572. {
  1573. $this->mergeCells = $pValue;
  1574. return $this;
  1575. }
  1576. /**
  1577. * Set protection on a cell range.
  1578. *
  1579. * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
  1580. * @param string $pPassword Password to unlock the protection
  1581. * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
  1582. *
  1583. * @return Worksheet
  1584. */
  1585. public function protectCells($pRange, $pPassword, $pAlreadyHashed = false)
  1586. {
  1587. // Uppercase coordinate
  1588. $pRange = strtoupper($pRange);
  1589. if (!$pAlreadyHashed) {
  1590. $pPassword = Shared\PasswordHasher::hashPassword($pPassword);
  1591. }
  1592. $this->protectedCells[$pRange] = $pPassword;
  1593. return $this;
  1594. }
  1595. /**
  1596. * Set protection on a cell range by using numeric cell coordinates.
  1597. *
  1598. * @param int $columnIndex1 Numeric column coordinate of the first cell
  1599. * @param int $row1 Numeric row coordinate of the first cell
  1600. * @param int $columnIndex2 Numeric column coordinate of the last cell
  1601. * @param int $row2 Numeric row coordinate of the last cell
  1602. * @param string $password Password to unlock the protection
  1603. * @param bool $alreadyHashed If the password has already been hashed, set this to true
  1604. *
  1605. * @return Worksheet
  1606. */
  1607. public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false)
  1608. {
  1609. $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
  1610. return $this->protectCells($cellRange, $password, $alreadyHashed);
  1611. }
  1612. /**
  1613. * Remove protection on a cell range.
  1614. *
  1615. * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
  1616. *
  1617. * @throws Exception
  1618. *
  1619. * @return Worksheet
  1620. */
  1621. public function unprotectCells($pRange)
  1622. {
  1623. // Uppercase coordinate
  1624. $pRange = strtoupper($pRange);
  1625. if (isset($this->protectedCells[$pRange])) {
  1626. unset($this->protectedCells[$pRange]);
  1627. } else {
  1628. throw new Exception('Cell range ' . $pRange . ' not known as protected.');
  1629. }
  1630. return $this;
  1631. }
  1632. /**
  1633. * Remove protection on a cell range by using numeric cell coordinates.
  1634. *
  1635. * @param int $columnIndex1 Numeric column coordinate of the first cell
  1636. * @param int $row1 Numeric row coordinate of the first cell
  1637. * @param int $columnIndex2 Numeric column coordinate of the last cell
  1638. * @param int $row2 Numeric row coordinate of the last cell
  1639. *
  1640. * @throws Exception
  1641. *
  1642. * @return Worksheet
  1643. */
  1644. public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
  1645. {
  1646. $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
  1647. return $this->unprotectCells($cellRange);
  1648. }
  1649. /**
  1650. * Get protected cells.
  1651. *
  1652. * @return array[]
  1653. */
  1654. public function getProtectedCells()
  1655. {
  1656. return $this->protectedCells;
  1657. }
  1658. /**
  1659. * Get Autofilter.
  1660. *
  1661. * @return AutoFilter
  1662. */
  1663. public function getAutoFilter()
  1664. {
  1665. return $this->autoFilter;
  1666. }
  1667. /**
  1668. * Set AutoFilter.
  1669. *
  1670. * @param AutoFilter|string $pValue
  1671. * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
  1672. *
  1673. * @throws Exception
  1674. *
  1675. * @return Worksheet
  1676. */
  1677. public function setAutoFilter($pValue)
  1678. {
  1679. if (is_string($pValue)) {
  1680. $this->autoFilter->setRange($pValue);
  1681. } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) {
  1682. $this->autoFilter = $pValue;
  1683. }
  1684. return $this;
  1685. }
  1686. /**
  1687. * Set Autofilter Range by using numeric cell coordinates.
  1688. *
  1689. * @param int $columnIndex1 Numeric column coordinate of the first cell
  1690. * @param int $row1 Numeric row coordinate of the first cell
  1691. * @param int $columnIndex2 Numeric column coordinate of the second cell
  1692. * @param int $row2 Numeric row coordinate of the second cell
  1693. *
  1694. * @throws Exception
  1695. *
  1696. * @return Worksheet
  1697. */
  1698. public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
  1699. {
  1700. return $this->setAutoFilter(
  1701. Coordinate::stringFromColumnIndex($columnIndex1) . $row1
  1702. . ':' .
  1703. Coordinate::stringFromColumnIndex($columnIndex2) . $row2
  1704. );
  1705. }
  1706. /**
  1707. * Remove autofilter.
  1708. *
  1709. * @return Worksheet
  1710. */
  1711. public function removeAutoFilter()
  1712. {
  1713. $this->autoFilter->setRange(null);
  1714. return $this;
  1715. }
  1716. /**
  1717. * Get Freeze Pane.
  1718. *
  1719. * @return string
  1720. */
  1721. public function getFreezePane()
  1722. {
  1723. return $this->freezePane;
  1724. }
  1725. /**
  1726. * Freeze Pane.
  1727. *
  1728. * Examples:
  1729. *
  1730. * - A2 will freeze the rows above cell A2 (i.e row 1)
  1731. * - B1 will freeze the columns to the left of cell B1 (i.e column A)
  1732. * - B2 will freeze the rows above and to the left of cell A2 (i.e row 1 and column A)
  1733. *
  1734. * @param null|string $cell Position of the split
  1735. * @param null|string $topLeftCell default position of the right bottom pane
  1736. *
  1737. * @throws Exception
  1738. *
  1739. * @return Worksheet
  1740. */
  1741. public function freezePane($cell, $topLeftCell = null)
  1742. {
  1743. if (is_string($cell) && Coordinate::coordinateIsRange($cell)) {
  1744. throw new Exception('Freeze pane can not be set on a range of cells.');
  1745. }
  1746. if ($cell !== null && $topLeftCell === null) {
  1747. $coordinate = Coordinate::coordinateFromString($cell);
  1748. $topLeftCell = $coordinate[0] . ($coordinate[1] + 1);
  1749. }
  1750. $this->freezePane = $cell;
  1751. $this->topLeftCell = $topLeftCell;
  1752. return $this;
  1753. }
  1754. /**
  1755. * Freeze Pane by using numeric cell coordinates.
  1756. *
  1757. * @param int $columnIndex Numeric column coordinate of the cell
  1758. * @param int $row Numeric row coordinate of the cell
  1759. *
  1760. * @return Worksheet
  1761. */
  1762. public function freezePaneByColumnAndRow($columnIndex, $row)
  1763. {
  1764. return $this->freezePane(Coordinate::stringFromColumnIndex($columnIndex) . $row);
  1765. }
  1766. /**
  1767. * Unfreeze Pane.
  1768. *
  1769. * @return Worksheet
  1770. */
  1771. public function unfreezePane()
  1772. {
  1773. return $this->freezePane(null);
  1774. }
  1775. /**
  1776. * Get the default position of the right bottom pane.
  1777. *
  1778. * @return int
  1779. */
  1780. public function getTopLeftCell()
  1781. {
  1782. return $this->topLeftCell;
  1783. }
  1784. /**
  1785. * Insert a new row, updating all possible related data.
  1786. *
  1787. * @param int $pBefore Insert before this one
  1788. * @param int $pNumRows Number of rows to insert
  1789. *
  1790. * @throws Exception
  1791. *
  1792. * @return Worksheet
  1793. */
  1794. public function insertNewRowBefore($pBefore, $pNumRows = 1)
  1795. {
  1796. if ($pBefore >= 1) {
  1797. $objReferenceHelper = ReferenceHelper::getInstance();
  1798. $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
  1799. } else {
  1800. throw new Exception('Rows can only be inserted before at least row 1.');
  1801. }
  1802. return $this;
  1803. }
  1804. /**
  1805. * Insert a new column, updating all possible related data.
  1806. *
  1807. * @param int $pBefore Insert before this one, eg: 'A'
  1808. * @param int $pNumCols Number of columns to insert
  1809. *
  1810. * @throws Exception
  1811. *
  1812. * @return Worksheet
  1813. */
  1814. public function insertNewColumnBefore($pBefore, $pNumCols = 1)
  1815. {
  1816. if (!is_numeric($pBefore)) {
  1817. $objReferenceHelper = ReferenceHelper::getInstance();
  1818. $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
  1819. } else {
  1820. throw new Exception('Column references should not be numeric.');
  1821. }
  1822. return $this;
  1823. }
  1824. /**
  1825. * Insert a new column, updating all possible related data.
  1826. *
  1827. * @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell)
  1828. * @param int $pNumCols Number of columns to insert
  1829. *
  1830. * @throws Exception
  1831. *
  1832. * @return Worksheet
  1833. */
  1834. public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1)
  1835. {
  1836. if ($beforeColumnIndex >= 1) {
  1837. return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $pNumCols);
  1838. }
  1839. throw new Exception('Columns can only be inserted before at least column A (1).');
  1840. }
  1841. /**
  1842. * Delete a row, updating all possible related data.
  1843. *
  1844. * @param int $pRow Remove starting with this one
  1845. * @param int $pNumRows Number of rows to remove
  1846. *
  1847. * @throws Exception
  1848. *
  1849. * @return Worksheet
  1850. */
  1851. public function removeRow($pRow, $pNumRows = 1)
  1852. {
  1853. if ($pRow >= 1) {
  1854. $highestRow = $this->getHighestDataRow();
  1855. $objReferenceHelper = ReferenceHelper::getInstance();
  1856. $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this);
  1857. for ($r = 0; $r < $pNumRows; ++$r) {
  1858. $this->getCellCollection()->removeRow($highestRow);
  1859. --$highestRow;
  1860. }
  1861. } else {
  1862. throw new Exception('Rows to be deleted should at least start from row 1.');
  1863. }
  1864. return $this;
  1865. }
  1866. /**
  1867. * Remove a column, updating all possible related data.
  1868. *
  1869. * @param string $pColumn Remove starting with this one, eg: 'A'
  1870. * @param int $pNumCols Number of columns to remove
  1871. *
  1872. * @throws Exception
  1873. *
  1874. * @return Worksheet
  1875. */
  1876. public function removeColumn($pColumn, $pNumCols = 1)
  1877. {
  1878. if (!is_numeric($pColumn)) {
  1879. $highestColumn = $this->getHighestDataColumn();
  1880. $pColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($pColumn) + $pNumCols);
  1881. $objReferenceHelper = ReferenceHelper::getInstance();
  1882. $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this);
  1883. for ($c = 0; $c < $pNumCols; ++$c) {
  1884. $this->getCellCollection()->removeColumn($highestColumn);
  1885. $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
  1886. }
  1887. } else {
  1888. throw new Exception('Column references should not be numeric.');
  1889. }
  1890. return $this;
  1891. }
  1892. /**
  1893. * Remove a column, updating all possible related data.
  1894. *
  1895. * @param int $columnIndex Remove starting with this one (numeric column coordinate of the cell)
  1896. * @param int $numColumns Number of columns to remove
  1897. *
  1898. * @throws Exception
  1899. *
  1900. * @return Worksheet
  1901. */
  1902. public function removeColumnByIndex($columnIndex, $numColumns = 1)
  1903. {
  1904. if ($columnIndex >= 1) {
  1905. return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
  1906. }
  1907. throw new Exception('Columns to be deleted should at least start from column A (1)');
  1908. }
  1909. /**
  1910. * Show gridlines?
  1911. *
  1912. * @return bool
  1913. */
  1914. public function getShowGridlines()
  1915. {
  1916. return $this->showGridlines;
  1917. }
  1918. /**
  1919. * Set show gridlines.
  1920. *
  1921. * @param bool $pValue Show gridlines (true/false)
  1922. *
  1923. * @return Worksheet
  1924. */
  1925. public function setShowGridlines($pValue)
  1926. {
  1927. $this->showGridlines = $pValue;
  1928. return $this;
  1929. }
  1930. /**
  1931. * Print gridlines?
  1932. *
  1933. * @return bool
  1934. */
  1935. public function getPrintGridlines()
  1936. {
  1937. return $this->printGridlines;
  1938. }
  1939. /**
  1940. * Set print gridlines.
  1941. *
  1942. * @param bool $pValue Print gridlines (true/false)
  1943. *
  1944. * @return Worksheet
  1945. */
  1946. public function setPrintGridlines($pValue)
  1947. {
  1948. $this->printGridlines = $pValue;
  1949. return $this;
  1950. }
  1951. /**
  1952. * Show row and column headers?
  1953. *
  1954. * @return bool
  1955. */
  1956. public function getShowRowColHeaders()
  1957. {
  1958. return $this->showRowColHeaders;
  1959. }
  1960. /**
  1961. * Set show row and column headers.
  1962. *
  1963. * @param bool $pValue Show row and column headers (true/false)
  1964. *
  1965. * @return Worksheet
  1966. */
  1967. public function setShowRowColHeaders($pValue)
  1968. {
  1969. $this->showRowColHeaders = $pValue;
  1970. return $this;
  1971. }
  1972. /**
  1973. * Show summary below? (Row/Column outlining).
  1974. *
  1975. * @return bool
  1976. */
  1977. public function getShowSummaryBelow()
  1978. {
  1979. return $this->showSummaryBelow;
  1980. }
  1981. /**
  1982. * Set show summary below.
  1983. *
  1984. * @param bool $pValue Show summary below (true/false)
  1985. *
  1986. * @return Worksheet
  1987. */
  1988. public function setShowSummaryBelow($pValue)
  1989. {
  1990. $this->showSummaryBelow = $pValue;
  1991. return $this;
  1992. }
  1993. /**
  1994. * Show summary right? (Row/Column outlining).
  1995. *
  1996. * @return bool
  1997. */
  1998. public function getShowSummaryRight()
  1999. {
  2000. return $this->showSummaryRight;
  2001. }
  2002. /**
  2003. * Set show summary right.
  2004. *
  2005. * @param bool $pValue Show summary right (true/false)
  2006. *
  2007. * @return Worksheet
  2008. */
  2009. public function setShowSummaryRight($pValue)
  2010. {
  2011. $this->showSummaryRight = $pValue;
  2012. return $this;
  2013. }
  2014. /**
  2015. * Get comments.
  2016. *
  2017. * @return Comment[]
  2018. */
  2019. public function getComments()
  2020. {
  2021. return $this->comments;
  2022. }
  2023. /**
  2024. * Set comments array for the entire sheet.
  2025. *
  2026. * @param Comment[] $pValue
  2027. *
  2028. * @return Worksheet
  2029. */
  2030. public function setComments(array $pValue)
  2031. {
  2032. $this->comments = $pValue;
  2033. return $this;
  2034. }
  2035. /**
  2036. * Get comment for cell.
  2037. *
  2038. * @param string $pCellCoordinate Cell coordinate to get comment for, eg: 'A1'
  2039. *
  2040. * @throws Exception
  2041. *
  2042. * @return Comment
  2043. */
  2044. public function getComment($pCellCoordinate)
  2045. {
  2046. // Uppercase coordinate
  2047. $pCellCoordinate = strtoupper($pCellCoordinate);
  2048. if (Coordinate::coordinateIsRange($pCellCoordinate)) {
  2049. throw new Exception('Cell coordinate string can not be a range of cells.');
  2050. } elseif (strpos($pCellCoordinate, '$') !== false) {
  2051. throw new Exception('Cell coordinate string must not be absolute.');
  2052. } elseif ($pCellCoordinate == '') {
  2053. throw new Exception('Cell coordinate can not be zero-length string.');
  2054. }
  2055. // Check if we already have a comment for this cell.
  2056. if (isset($this->comments[$pCellCoordinate])) {
  2057. return $this->comments[$pCellCoordinate];
  2058. }
  2059. // If not, create a new comment.
  2060. $newComment = new Comment();
  2061. $this->comments[$pCellCoordinate] = $newComment;
  2062. return $newComment;
  2063. }
  2064. /**
  2065. * Get comment for cell by using numeric cell coordinates.
  2066. *
  2067. * @param int $columnIndex Numeric column coordinate of the cell
  2068. * @param int $row Numeric row coordinate of the cell
  2069. *
  2070. * @return Comment
  2071. */
  2072. public function getCommentByColumnAndRow($columnIndex, $row)
  2073. {
  2074. return $this->getComment(Coordinate::stringFromColumnIndex($columnIndex) . $row);
  2075. }
  2076. /**
  2077. * Get active cell.
  2078. *
  2079. * @return string Example: 'A1'
  2080. */
  2081. public function getActiveCell()
  2082. {
  2083. return $this->activeCell;
  2084. }
  2085. /**
  2086. * Get selected cells.
  2087. *
  2088. * @return string
  2089. */
  2090. public function getSelectedCells()
  2091. {
  2092. return $this->selectedCells;
  2093. }
  2094. /**
  2095. * Selected cell.
  2096. *
  2097. * @param string $pCoordinate Cell (i.e. A1)
  2098. *
  2099. * @return Worksheet
  2100. */
  2101. public function setSelectedCell($pCoordinate)
  2102. {
  2103. return $this->setSelectedCells($pCoordinate);
  2104. }
  2105. /**
  2106. * Select a range of cells.
  2107. *
  2108. * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
  2109. *
  2110. * @return Worksheet
  2111. */
  2112. public function setSelectedCells($pCoordinate)
  2113. {
  2114. // Uppercase coordinate
  2115. $pCoordinate = strtoupper($pCoordinate);
  2116. // Convert 'A' to 'A:A'
  2117. $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate);
  2118. // Convert '1' to '1:1'
  2119. $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate);
  2120. // Convert 'A:C' to 'A1:C1048576'
  2121. $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate);
  2122. // Convert '1:3' to 'A1:XFD3'
  2123. $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate);
  2124. if (Coordinate::coordinateIsRange($pCoordinate)) {
  2125. list($first) = Coordinate::splitRange($pCoordinate);
  2126. $this->activeCell = $first[0];
  2127. } else {
  2128. $this->activeCell = $pCoordinate;
  2129. }
  2130. $this->selectedCells = $pCoordinate;
  2131. return $this;
  2132. }
  2133. /**
  2134. * Selected cell by using numeric cell coordinates.
  2135. *
  2136. * @param int $columnIndex Numeric column coordinate of the cell
  2137. * @param int $row Numeric row coordinate of the cell
  2138. *
  2139. * @throws Exception
  2140. *
  2141. * @return Worksheet
  2142. */
  2143. public function setSelectedCellByColumnAndRow($columnIndex, $row)
  2144. {
  2145. return $this->setSelectedCells(Coordinate::stringFromColumnIndex($columnIndex) . $row);
  2146. }
  2147. /**
  2148. * Get right-to-left.
  2149. *
  2150. * @return bool
  2151. */
  2152. public function getRightToLeft()
  2153. {
  2154. return $this->rightToLeft;
  2155. }
  2156. /**
  2157. * Set right-to-left.
  2158. *
  2159. * @param bool $value Right-to-left true/false
  2160. *
  2161. * @return Worksheet
  2162. */
  2163. public function setRightToLeft($value)
  2164. {
  2165. $this->rightToLeft = $value;
  2166. return $this;
  2167. }
  2168. /**
  2169. * Fill worksheet from values in array.
  2170. *
  2171. * @param array $source Source array
  2172. * @param mixed $nullValue Value in source array that stands for blank cell
  2173. * @param string $startCell Insert array starting from this cell address as the top left coordinate
  2174. * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
  2175. *
  2176. * @throws Exception
  2177. *
  2178. * @return Worksheet
  2179. */
  2180. public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
  2181. {
  2182. // Convert a 1-D array to 2-D (for ease of looping)
  2183. if (!is_array(end($source))) {
  2184. $source = [$source];
  2185. }
  2186. // start coordinate
  2187. list($startColumn, $startRow) = Coordinate::coordinateFromString($startCell);
  2188. // Loop through $source
  2189. foreach ($source as $rowData) {
  2190. $currentColumn = $startColumn;
  2191. foreach ($rowData as $cellValue) {
  2192. if ($strictNullComparison) {
  2193. if ($cellValue !== $nullValue) {
  2194. // Set cell value
  2195. $this->getCell($currentColumn . $startRow)->setValue($cellValue);
  2196. }
  2197. } else {
  2198. if ($cellValue != $nullValue) {
  2199. // Set cell value
  2200. $this->getCell($currentColumn . $startRow)->setValue($cellValue);
  2201. }
  2202. }
  2203. ++$currentColumn;
  2204. }
  2205. ++$startRow;
  2206. }
  2207. return $this;
  2208. }
  2209. /**
  2210. * Create array from a range of cells.
  2211. *
  2212. * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
  2213. * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
  2214. * @param bool $calculateFormulas Should formulas be calculated?
  2215. * @param bool $formatData Should formatting be applied to cell values?
  2216. * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
  2217. * True - Return rows and columns indexed by their actual row and column IDs
  2218. *
  2219. * @return array
  2220. */
  2221. public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
  2222. {
  2223. // Returnvalue
  2224. $returnValue = [];
  2225. // Identify the range that we need to extract from the worksheet
  2226. list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange);
  2227. $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
  2228. $minRow = $rangeStart[1];
  2229. $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
  2230. $maxRow = $rangeEnd[1];
  2231. ++$maxCol;
  2232. // Loop through rows
  2233. $r = -1;
  2234. for ($row = $minRow; $row <= $maxRow; ++$row) {
  2235. $rRef = ($returnCellRef) ? $row : ++$r;
  2236. $c = -1;
  2237. // Loop through columns in the current row
  2238. for ($col = $minCol; $col != $maxCol; ++$col) {
  2239. $cRef = ($returnCellRef) ? $col : ++$c;
  2240. // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
  2241. // so we test and retrieve directly against cellCollection
  2242. if ($this->cellCollection->has($col . $row)) {
  2243. // Cell exists
  2244. $cell = $this->cellCollection->get($col . $row);
  2245. if ($cell->getValue() !== null) {
  2246. if ($cell->getValue() instanceof RichText) {
  2247. $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
  2248. } else {
  2249. if ($calculateFormulas) {
  2250. $returnValue[$rRef][$cRef] = $cell->getCalculatedValue();
  2251. } else {
  2252. $returnValue[$rRef][$cRef] = $cell->getValue();
  2253. }
  2254. }
  2255. if ($formatData) {
  2256. $style = $this->parent->getCellXfByIndex($cell->getXfIndex());
  2257. $returnValue[$rRef][$cRef] = NumberFormat::toFormattedString(
  2258. $returnValue[$rRef][$cRef],
  2259. ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL
  2260. );
  2261. }
  2262. } else {
  2263. // Cell holds a NULL
  2264. $returnValue[$rRef][$cRef] = $nullValue;
  2265. }
  2266. } else {
  2267. // Cell doesn't exist
  2268. $returnValue[$rRef][$cRef] = $nullValue;
  2269. }
  2270. }
  2271. }
  2272. // Return
  2273. return $returnValue;
  2274. }
  2275. /**
  2276. * Create array from a range of cells.
  2277. *
  2278. * @param string $pNamedRange Name of the Named Range
  2279. * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
  2280. * @param bool $calculateFormulas Should formulas be calculated?
  2281. * @param bool $formatData Should formatting be applied to cell values?
  2282. * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
  2283. * True - Return rows and columns indexed by their actual row and column IDs
  2284. *
  2285. * @throws Exception
  2286. *
  2287. * @return array
  2288. */
  2289. public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
  2290. {
  2291. $namedRange = NamedRange::resolveRange($pNamedRange, $this);
  2292. if ($namedRange !== null) {
  2293. $pWorkSheet = $namedRange->getWorksheet();
  2294. $pCellRange = $namedRange->getRange();
  2295. return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
  2296. }
  2297. throw new Exception('Named Range ' . $pNamedRange . ' does not exist.');
  2298. }
  2299. /**
  2300. * Create array from worksheet.
  2301. *
  2302. * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
  2303. * @param bool $calculateFormulas Should formulas be calculated?
  2304. * @param bool $formatData Should formatting be applied to cell values?
  2305. * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
  2306. * True - Return rows and columns indexed by their actual row and column IDs
  2307. *
  2308. * @return array
  2309. */
  2310. public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
  2311. {
  2312. // Garbage collect...
  2313. $this->garbageCollect();
  2314. // Identify the range that we need to extract from the worksheet
  2315. $maxCol = $this->getHighestColumn();
  2316. $maxRow = $this->getHighestRow();
  2317. // Return
  2318. return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
  2319. }
  2320. /**
  2321. * Get row iterator.
  2322. *
  2323. * @param int $startRow The row number at which to start iterating
  2324. * @param int $endRow The row number at which to stop iterating
  2325. *
  2326. * @return RowIterator
  2327. */
  2328. public function getRowIterator($startRow = 1, $endRow = null)
  2329. {
  2330. return new RowIterator($this, $startRow, $endRow);
  2331. }
  2332. /**
  2333. * Get column iterator.
  2334. *
  2335. * @param string $startColumn The column address at which to start iterating
  2336. * @param string $endColumn The column address at which to stop iterating
  2337. *
  2338. * @return ColumnIterator
  2339. */
  2340. public function getColumnIterator($startColumn = 'A', $endColumn = null)
  2341. {
  2342. return new ColumnIterator($this, $startColumn, $endColumn);
  2343. }
  2344. /**
  2345. * Run PhpSpreadsheet garbage collector.
  2346. *
  2347. * @return Worksheet
  2348. */
  2349. public function garbageCollect()
  2350. {
  2351. // Flush cache
  2352. $this->cellCollection->get('A1');
  2353. // Lookup highest column and highest row if cells are cleaned
  2354. $colRow = $this->cellCollection->getHighestRowAndColumn();
  2355. $highestRow = $colRow['row'];
  2356. $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
  2357. // Loop through column dimensions
  2358. foreach ($this->columnDimensions as $dimension) {
  2359. $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
  2360. }
  2361. // Loop through row dimensions
  2362. foreach ($this->rowDimensions as $dimension) {
  2363. $highestRow = max($highestRow, $dimension->getRowIndex());
  2364. }
  2365. // Cache values
  2366. if ($highestColumn < 1) {
  2367. $this->cachedHighestColumn = 'A';
  2368. } else {
  2369. $this->cachedHighestColumn = Coordinate::stringFromColumnIndex($highestColumn);
  2370. }
  2371. $this->cachedHighestRow = $highestRow;
  2372. // Return
  2373. return $this;
  2374. }
  2375. /**
  2376. * Get hash code.
  2377. *
  2378. * @return string Hash code
  2379. */
  2380. public function getHashCode()
  2381. {
  2382. if ($this->dirty) {
  2383. $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__);
  2384. $this->dirty = false;
  2385. }
  2386. return $this->hash;
  2387. }
  2388. /**
  2389. * Extract worksheet title from range.
  2390. *
  2391. * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
  2392. * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> array('testSheet 1', 'A1');
  2393. *
  2394. * @param string $pRange Range to extract title from
  2395. * @param bool $returnRange Return range? (see example)
  2396. *
  2397. * @return mixed
  2398. */
  2399. public static function extractSheetTitle($pRange, $returnRange = false)
  2400. {
  2401. // Sheet title included?
  2402. if (($sep = strpos($pRange, '!')) === false) {
  2403. return '';
  2404. }
  2405. if ($returnRange) {
  2406. return [trim(substr($pRange, 0, $sep), "'"), substr($pRange, $sep + 1)];
  2407. }
  2408. return substr($pRange, $sep + 1);
  2409. }
  2410. /**
  2411. * Get hyperlink.
  2412. *
  2413. * @param string $pCellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
  2414. *
  2415. * @return Hyperlink
  2416. */
  2417. public function getHyperlink($pCellCoordinate)
  2418. {
  2419. // return hyperlink if we already have one
  2420. if (isset($this->hyperlinkCollection[$pCellCoordinate])) {
  2421. return $this->hyperlinkCollection[$pCellCoordinate];
  2422. }
  2423. // else create hyperlink
  2424. $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink();
  2425. return $this->hyperlinkCollection[$pCellCoordinate];
  2426. }
  2427. /**
  2428. * Set hyperlink.
  2429. *
  2430. * @param string $pCellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
  2431. * @param null|Hyperlink $pHyperlink
  2432. *
  2433. * @return Worksheet
  2434. */
  2435. public function setHyperlink($pCellCoordinate, Hyperlink $pHyperlink = null)
  2436. {
  2437. if ($pHyperlink === null) {
  2438. unset($this->hyperlinkCollection[$pCellCoordinate]);
  2439. } else {
  2440. $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
  2441. }
  2442. return $this;
  2443. }
  2444. /**
  2445. * Hyperlink at a specific coordinate exists?
  2446. *
  2447. * @param string $pCoordinate eg: 'A1'
  2448. *
  2449. * @return bool
  2450. */
  2451. public function hyperlinkExists($pCoordinate)
  2452. {
  2453. return isset($this->hyperlinkCollection[$pCoordinate]);
  2454. }
  2455. /**
  2456. * Get collection of hyperlinks.
  2457. *
  2458. * @return Hyperlink[]
  2459. */
  2460. public function getHyperlinkCollection()
  2461. {
  2462. return $this->hyperlinkCollection;
  2463. }
  2464. /**
  2465. * Get data validation.
  2466. *
  2467. * @param string $pCellCoordinate Cell coordinate to get data validation for, eg: 'A1'
  2468. *
  2469. * @return DataValidation
  2470. */
  2471. public function getDataValidation($pCellCoordinate)
  2472. {
  2473. // return data validation if we already have one
  2474. if (isset($this->dataValidationCollection[$pCellCoordinate])) {
  2475. return $this->dataValidationCollection[$pCellCoordinate];
  2476. }
  2477. // else create data validation
  2478. $this->dataValidationCollection[$pCellCoordinate] = new DataValidation();
  2479. return $this->dataValidationCollection[$pCellCoordinate];
  2480. }
  2481. /**
  2482. * Set data validation.
  2483. *
  2484. * @param string $pCellCoordinate Cell coordinate to insert data validation, eg: 'A1'
  2485. * @param null|DataValidation $pDataValidation
  2486. *
  2487. * @return Worksheet
  2488. */
  2489. public function setDataValidation($pCellCoordinate, DataValidation $pDataValidation = null)
  2490. {
  2491. if ($pDataValidation === null) {
  2492. unset($this->dataValidationCollection[$pCellCoordinate]);
  2493. } else {
  2494. $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation;
  2495. }
  2496. return $this;
  2497. }
  2498. /**
  2499. * Data validation at a specific coordinate exists?
  2500. *
  2501. * @param string $pCoordinate eg: 'A1'
  2502. *
  2503. * @return bool
  2504. */
  2505. public function dataValidationExists($pCoordinate)
  2506. {
  2507. return isset($this->dataValidationCollection[$pCoordinate]);
  2508. }
  2509. /**
  2510. * Get collection of data validations.
  2511. *
  2512. * @return DataValidation[]
  2513. */
  2514. public function getDataValidationCollection()
  2515. {
  2516. return $this->dataValidationCollection;
  2517. }
  2518. /**
  2519. * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
  2520. *
  2521. * @param string $range
  2522. *
  2523. * @return string Adjusted range value
  2524. */
  2525. public function shrinkRangeToFit($range)
  2526. {
  2527. $maxCol = $this->getHighestColumn();
  2528. $maxRow = $this->getHighestRow();
  2529. $maxCol = Coordinate::columnIndexFromString($maxCol);
  2530. $rangeBlocks = explode(' ', $range);
  2531. foreach ($rangeBlocks as &$rangeSet) {
  2532. $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
  2533. if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
  2534. $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
  2535. }
  2536. if ($rangeBoundaries[0][1] > $maxRow) {
  2537. $rangeBoundaries[0][1] = $maxRow;
  2538. }
  2539. if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
  2540. $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
  2541. }
  2542. if ($rangeBoundaries[1][1] > $maxRow) {
  2543. $rangeBoundaries[1][1] = $maxRow;
  2544. }
  2545. $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
  2546. }
  2547. unset($rangeSet);
  2548. $stRange = implode(' ', $rangeBlocks);
  2549. return $stRange;
  2550. }
  2551. /**
  2552. * Get tab color.
  2553. *
  2554. * @return Color
  2555. */
  2556. public function getTabColor()
  2557. {
  2558. if ($this->tabColor === null) {
  2559. $this->tabColor = new Color();
  2560. }
  2561. return $this->tabColor;
  2562. }
  2563. /**
  2564. * Reset tab color.
  2565. *
  2566. * @return Worksheet
  2567. */
  2568. public function resetTabColor()
  2569. {
  2570. $this->tabColor = null;
  2571. unset($this->tabColor);
  2572. return $this;
  2573. }
  2574. /**
  2575. * Tab color set?
  2576. *
  2577. * @return bool
  2578. */
  2579. public function isTabColorSet()
  2580. {
  2581. return $this->tabColor !== null;
  2582. }
  2583. /**
  2584. * Copy worksheet (!= clone!).
  2585. *
  2586. * @return Worksheet
  2587. */
  2588. public function copy()
  2589. {
  2590. $copied = clone $this;
  2591. return $copied;
  2592. }
  2593. /**
  2594. * Implement PHP __clone to create a deep clone, not just a shallow copy.
  2595. */
  2596. public function __clone()
  2597. {
  2598. foreach ($this as $key => $val) {
  2599. if ($key == 'parent') {
  2600. continue;
  2601. }
  2602. if (is_object($val) || (is_array($val))) {
  2603. if ($key == 'cellCollection') {
  2604. $newCollection = $this->cellCollection->cloneCellCollection($this);
  2605. $this->cellCollection = $newCollection;
  2606. } elseif ($key == 'drawingCollection') {
  2607. $newCollection = new ArrayObject();
  2608. foreach ($this->drawingCollection as $id => $item) {
  2609. if (is_object($item)) {
  2610. $newCollection[$id] = clone $this->drawingCollection[$id];
  2611. }
  2612. }
  2613. $this->drawingCollection = $newCollection;
  2614. } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
  2615. $newAutoFilter = clone $this->autoFilter;
  2616. $this->autoFilter = $newAutoFilter;
  2617. $this->autoFilter->setParent($this);
  2618. } else {
  2619. $this->{$key} = unserialize(serialize($val));
  2620. }
  2621. }
  2622. }
  2623. }
  2624. /**
  2625. * Define the code name of the sheet.
  2626. *
  2627. * @param string $pValue Same rule as Title minus space not allowed (but, like Excel, change
  2628. * silently space to underscore)
  2629. * @param bool $validate False to skip validation of new title. WARNING: This should only be set
  2630. * at parse time (by Readers), where titles can be assumed to be valid.
  2631. *
  2632. * @throws Exception
  2633. *
  2634. * @return Worksheet
  2635. */
  2636. public function setCodeName($pValue, $validate = true)
  2637. {
  2638. // Is this a 'rename' or not?
  2639. if ($this->getCodeName() == $pValue) {
  2640. return $this;
  2641. }
  2642. if ($validate) {
  2643. $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same
  2644. // Syntax check
  2645. // throw an exception if not valid
  2646. self::checkSheetCodeName($pValue);
  2647. // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
  2648. if ($this->getParent()) {
  2649. // Is there already such sheet name?
  2650. if ($this->getParent()->sheetCodeNameExists($pValue)) {
  2651. // Use name, but append with lowest possible integer
  2652. if (Shared\StringHelper::countCharacters($pValue) > 29) {
  2653. $pValue = Shared\StringHelper::substring($pValue, 0, 29);
  2654. }
  2655. $i = 1;
  2656. while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) {
  2657. ++$i;
  2658. if ($i == 10) {
  2659. if (Shared\StringHelper::countCharacters($pValue) > 28) {
  2660. $pValue = Shared\StringHelper::substring($pValue, 0, 28);
  2661. }
  2662. } elseif ($i == 100) {
  2663. if (Shared\StringHelper::countCharacters($pValue) > 27) {
  2664. $pValue = Shared\StringHelper::substring($pValue, 0, 27);
  2665. }
  2666. }
  2667. }
  2668. $pValue = $pValue . '_' . $i; // ok, we have a valid name
  2669. }
  2670. }
  2671. }
  2672. $this->codeName = $pValue;
  2673. return $this;
  2674. }
  2675. /**
  2676. * Return the code name of the sheet.
  2677. *
  2678. * @return null|string
  2679. */
  2680. public function getCodeName()
  2681. {
  2682. return $this->codeName;
  2683. }
  2684. /**
  2685. * Sheet has a code name ?
  2686. *
  2687. * @return bool
  2688. */
  2689. public function hasCodeName()
  2690. {
  2691. return !($this->codeName === null);
  2692. }
  2693. }