Worksheet.php 86 KB

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