You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CellUtil.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.util;
  16. import java.util.Arrays;
  17. import java.util.Collections;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.Locale;
  21. import java.util.Map;
  22. import java.util.Set;
  23. import org.apache.logging.log4j.LogManager;
  24. import org.apache.logging.log4j.Logger;
  25. import org.apache.poi.ss.usermodel.BorderStyle;
  26. import org.apache.poi.ss.usermodel.Cell;
  27. import org.apache.poi.ss.usermodel.CellStyle;
  28. import org.apache.poi.ss.usermodel.FillPatternType;
  29. import org.apache.poi.ss.usermodel.Font;
  30. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  31. import org.apache.poi.ss.usermodel.Row;
  32. import org.apache.poi.ss.usermodel.Sheet;
  33. import org.apache.poi.ss.usermodel.VerticalAlignment;
  34. import org.apache.poi.ss.usermodel.Workbook;
  35. /**
  36. * Various utility functions that make working with a cells and rows easier. The various methods
  37. * that deal with style's allow you to create your CellStyles as you need them. When you apply a
  38. * style change to a cell, the code will attempt to see if a style already exists that meets your
  39. * needs. If not, then it will create a new style. This is to prevent creating too many styles.
  40. * there is an upper limit in Excel on the number of styles that can be supported.
  41. *
  42. *@author Eric Pugh epugh@upstate.com
  43. *@author (secondary) Avinash Kewalramani akewalramani@accelrys.com
  44. */
  45. public final class CellUtil {
  46. private static final Logger LOGGER = LogManager.getLogger(CellUtil.class);
  47. // FIXME: Move these constants into an enum
  48. public static final String ALIGNMENT = "alignment";
  49. public static final String BORDER_BOTTOM = "borderBottom";
  50. public static final String BORDER_LEFT = "borderLeft";
  51. public static final String BORDER_RIGHT = "borderRight";
  52. public static final String BORDER_TOP = "borderTop";
  53. public static final String BOTTOM_BORDER_COLOR = "bottomBorderColor";
  54. public static final String LEFT_BORDER_COLOR = "leftBorderColor";
  55. public static final String RIGHT_BORDER_COLOR = "rightBorderColor";
  56. public static final String TOP_BORDER_COLOR = "topBorderColor";
  57. public static final String DATA_FORMAT = "dataFormat";
  58. public static final String FILL_BACKGROUND_COLOR = "fillBackgroundColor";
  59. public static final String FILL_FOREGROUND_COLOR = "fillForegroundColor";
  60. public static final String FILL_PATTERN = "fillPattern";
  61. public static final String FONT = "font";
  62. public static final String HIDDEN = "hidden";
  63. public static final String INDENTION = "indention";
  64. public static final String LOCKED = "locked";
  65. public static final String ROTATION = "rotation";
  66. public static final String VERTICAL_ALIGNMENT = "verticalAlignment";
  67. public static final String WRAP_TEXT = "wrapText";
  68. private static final Set<String> shortValues = Collections.unmodifiableSet(
  69. new HashSet<>(Arrays.asList(
  70. BOTTOM_BORDER_COLOR,
  71. LEFT_BORDER_COLOR,
  72. RIGHT_BORDER_COLOR,
  73. TOP_BORDER_COLOR,
  74. FILL_FOREGROUND_COLOR,
  75. FILL_BACKGROUND_COLOR,
  76. INDENTION,
  77. DATA_FORMAT,
  78. ROTATION
  79. )));
  80. private static final Set<String> intValues = Collections.unmodifiableSet(
  81. new HashSet<>(Arrays.asList(
  82. FONT
  83. )));
  84. private static final Set<String> booleanValues = Collections.unmodifiableSet(
  85. new HashSet<>(Arrays.asList(
  86. LOCKED,
  87. HIDDEN,
  88. WRAP_TEXT
  89. )));
  90. private static final Set<String> borderTypeValues = Collections.unmodifiableSet(
  91. new HashSet<>(Arrays.asList(
  92. BORDER_BOTTOM,
  93. BORDER_LEFT,
  94. BORDER_RIGHT,
  95. BORDER_TOP
  96. )));
  97. private static UnicodeMapping[] unicodeMappings;
  98. private static final class UnicodeMapping {
  99. public final String entityName;
  100. public final String resolvedValue;
  101. public UnicodeMapping(String pEntityName, String pResolvedValue) {
  102. entityName = "&" + pEntityName + ";";
  103. resolvedValue = pResolvedValue;
  104. }
  105. }
  106. private CellUtil() {
  107. // no instances of this class
  108. }
  109. /**
  110. * Get a row from the spreadsheet, and create it if it doesn't exist.
  111. *
  112. * @param rowIndex The 0 based row number
  113. * @param sheet The sheet that the row is part of.
  114. * @return The row indicated by the rowCounter
  115. */
  116. public static Row getRow(int rowIndex, Sheet sheet) {
  117. Row row = sheet.getRow(rowIndex);
  118. if (row == null) {
  119. row = sheet.createRow(rowIndex);
  120. }
  121. return row;
  122. }
  123. /**
  124. * Get a specific cell from a row. If the cell doesn't exist, then create it.
  125. *
  126. * @param row The row that the cell is part of
  127. * @param columnIndex The column index that the cell is in.
  128. * @return The cell indicated by the column.
  129. */
  130. public static Cell getCell(Row row, int columnIndex) {
  131. Cell cell = row.getCell(columnIndex);
  132. if (cell == null) {
  133. cell = row.createCell(columnIndex);
  134. }
  135. return cell;
  136. }
  137. /**
  138. * Creates a cell, gives it a value, and applies a style if provided
  139. *
  140. * @param row the row to create the cell in
  141. * @param column the column index to create the cell in
  142. * @param value The value of the cell
  143. * @param style If the style is not null, then set
  144. * @return A new Cell
  145. */
  146. public static Cell createCell(Row row, int column, String value, CellStyle style) {
  147. Cell cell = getCell(row, column);
  148. cell.setCellValue(cell.getRow().getSheet().getWorkbook().getCreationHelper()
  149. .createRichTextString(value));
  150. if (style != null) {
  151. cell.setCellStyle(style);
  152. }
  153. return cell;
  154. }
  155. /**
  156. * Create a cell, and give it a value.
  157. *
  158. *@param row the row to create the cell in
  159. *@param column the column index to create the cell in
  160. *@param value The value of the cell
  161. *@return A new Cell.
  162. */
  163. public static Cell createCell(Row row, int column, String value) {
  164. return createCell(row, column, value, null);
  165. }
  166. /**
  167. * Take a cell, and align it.
  168. *
  169. * This is superior to cell.getCellStyle().setAlignment(align) because
  170. * this method will not modify the CellStyle object that may be referenced
  171. * by multiple cells. Instead, this method will search for existing CellStyles
  172. * that match the desired CellStyle, creating a new CellStyle with the desired
  173. * style if no match exists.
  174. *
  175. * @param cell the cell to set the alignment for
  176. * @param align the horizontal alignment to use.
  177. *
  178. * @see HorizontalAlignment for alignment options
  179. * @since POI 3.15 beta 3
  180. */
  181. public static void setAlignment(Cell cell, HorizontalAlignment align) {
  182. setCellStyleProperty(cell, ALIGNMENT, align);
  183. }
  184. /**
  185. * Take a cell, and vertically align it.
  186. *
  187. * This is superior to cell.getCellStyle().setVerticalAlignment(align) because
  188. * this method will not modify the CellStyle object that may be referenced
  189. * by multiple cells. Instead, this method will search for existing CellStyles
  190. * that match the desired CellStyle, creating a new CellStyle with the desired
  191. * style if no match exists.
  192. *
  193. * @param cell the cell to set the alignment for
  194. * @param align the vertical alignment to use.
  195. *
  196. * @see VerticalAlignment for alignment options
  197. * @since POI 3.15 beta 3
  198. */
  199. public static void setVerticalAlignment(Cell cell, VerticalAlignment align) {
  200. setCellStyleProperty(cell, VERTICAL_ALIGNMENT, align);
  201. }
  202. /**
  203. * Take a cell, and apply a font to it
  204. *
  205. * @param cell the cell to set the alignment for
  206. * @param font The Font that you want to set.
  207. * @throws IllegalArgumentException if <tt>font</tt> and <tt>cell</tt> do not belong to the same workbook
  208. */
  209. public static void setFont(Cell cell, Font font) {
  210. // Check if font belongs to workbook
  211. Workbook wb = cell.getSheet().getWorkbook();
  212. final int fontIndex = font.getIndexAsInt();
  213. if (!wb.getFontAt(fontIndex).equals(font)) {
  214. throw new IllegalArgumentException("Font does not belong to this workbook");
  215. }
  216. // Check if cell belongs to workbook
  217. // (checked in setCellStyleProperty)
  218. setCellStyleProperty(cell, FONT, fontIndex);
  219. }
  220. /**
  221. * <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
  222. * current style plus styles properties in <code>properties</code>. A new style is created if the
  223. * workbook does not contain a matching style.</p>
  224. *
  225. * <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
  226. * same style.</p>
  227. *
  228. * <p>This is necessary because Excel has an upper limit on the number of styles that it supports.</p>
  229. *
  230. * <p>This function is more efficient than multiple calls to
  231. * {@link #setCellStyleProperty(Cell, String, Object)}
  232. * if adding multiple cell styles.</p>
  233. *
  234. * <p>For performance reasons, if this is the only cell in a workbook that uses a cell style,
  235. * this method does NOT remove the old style from the workbook.
  236. * <!-- NOT IMPLEMENTED: Unused styles should be
  237. * pruned from the workbook with [@link #removeUnusedCellStyles(Workbook)] or
  238. * [@link #removeStyleFromWorkbookIfUnused(CellStyle, Workbook)]. -->
  239. * </p>
  240. *
  241. * @param cell The cell to change the style of
  242. * @param properties The properties to be added to a cell style, as {propertyName: propertyValue}.
  243. * @since POI 3.14 beta 2
  244. */
  245. public static void setCellStyleProperties(Cell cell, Map<String, Object> properties) {
  246. Workbook workbook = cell.getSheet().getWorkbook();
  247. CellStyle originalStyle = cell.getCellStyle();
  248. CellStyle newStyle = null;
  249. Map<String, Object> values = getFormatProperties(originalStyle);
  250. putAll(properties, values);
  251. // index seems like what index the cellstyle is in the list of styles for a workbook.
  252. // not good to compare on!
  253. int numberCellStyles = workbook.getNumCellStyles();
  254. for (int i = 0; i < numberCellStyles; i++) {
  255. CellStyle wbStyle = workbook.getCellStyleAt(i);
  256. Map<String, Object> wbStyleMap = getFormatProperties(wbStyle);
  257. // the desired style already exists in the workbook. Use the existing style.
  258. if (wbStyleMap.equals(values)) {
  259. newStyle = wbStyle;
  260. break;
  261. }
  262. }
  263. // the desired style does not exist in the workbook. Create a new style with desired properties.
  264. if (newStyle == null) {
  265. newStyle = workbook.createCellStyle();
  266. setFormatProperties(newStyle, workbook, values);
  267. }
  268. cell.setCellStyle(newStyle);
  269. }
  270. /**
  271. * <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
  272. * current style plus a single style property <code>propertyName</code> with value
  273. * <code>propertyValue</code>.
  274. * A new style is created if the workbook does not contain a matching style.</p>
  275. *
  276. * <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
  277. * same style.</p>
  278. *
  279. * <p>If setting more than one cell style property on a cell, use
  280. * {@link #setCellStyleProperties(Cell, Map)},
  281. * which is faster and does not add unnecessary intermediate CellStyles to the workbook.</p>
  282. *
  283. * @param cell The cell that is to be changed.
  284. * @param propertyName The name of the property that is to be changed.
  285. * @param propertyValue The value of the property that is to be changed.
  286. */
  287. public static void setCellStyleProperty(Cell cell, String propertyName, Object propertyValue) {
  288. Map<String, Object> property = Collections.singletonMap(propertyName, propertyValue);
  289. setCellStyleProperties(cell, property);
  290. }
  291. /**
  292. * Returns a map containing the format properties of the given cell style.
  293. * The returned map is not tied to <code>style</code>, so subsequent changes
  294. * to <code>style</code> will not modify the map, and changes to the returned
  295. * map will not modify the cell style. The returned map is mutable.
  296. *
  297. * @param style cell style
  298. * @return map of format properties (String -> Object)
  299. * @see #setFormatProperties(CellStyle, Workbook, Map)
  300. */
  301. private static Map<String, Object> getFormatProperties(CellStyle style) {
  302. Map<String, Object> properties = new HashMap<>();
  303. put(properties, ALIGNMENT, style.getAlignment());
  304. put(properties, VERTICAL_ALIGNMENT, style.getVerticalAlignment());
  305. put(properties, BORDER_BOTTOM, style.getBorderBottom());
  306. put(properties, BORDER_LEFT, style.getBorderLeft());
  307. put(properties, BORDER_RIGHT, style.getBorderRight());
  308. put(properties, BORDER_TOP, style.getBorderTop());
  309. put(properties, BOTTOM_BORDER_COLOR, style.getBottomBorderColor());
  310. put(properties, DATA_FORMAT, style.getDataFormat());
  311. put(properties, FILL_PATTERN, style.getFillPattern());
  312. put(properties, FILL_FOREGROUND_COLOR, style.getFillForegroundColor());
  313. put(properties, FILL_BACKGROUND_COLOR, style.getFillBackgroundColor());
  314. put(properties, FONT, style.getFontIndex());
  315. put(properties, HIDDEN, style.getHidden());
  316. put(properties, INDENTION, style.getIndention());
  317. put(properties, LEFT_BORDER_COLOR, style.getLeftBorderColor());
  318. put(properties, LOCKED, style.getLocked());
  319. put(properties, RIGHT_BORDER_COLOR, style.getRightBorderColor());
  320. put(properties, ROTATION, style.getRotation());
  321. put(properties, TOP_BORDER_COLOR, style.getTopBorderColor());
  322. put(properties, WRAP_TEXT, style.getWrapText());
  323. return properties;
  324. }
  325. /**
  326. * Copies the entries in src to dest, using the preferential data type
  327. * so that maps can be compared for equality
  328. *
  329. * @param src the property map to copy from (read-only)
  330. * @param dest the property map to copy into
  331. * @since POI 3.15 beta 3
  332. */
  333. private static void putAll(final Map<String, Object> src, Map<String, Object> dest) {
  334. for (final String key : src.keySet()) {
  335. if (shortValues.contains(key)) {
  336. dest.put(key, getShort(src, key));
  337. } else if (intValues.contains(key)) {
  338. dest.put(key, getInt(src, key));
  339. } else if (booleanValues.contains(key)) {
  340. dest.put(key, getBoolean(src, key));
  341. } else if (borderTypeValues.contains(key)) {
  342. dest.put(key, getBorderStyle(src, key));
  343. } else if (ALIGNMENT.equals(key)) {
  344. dest.put(key, getHorizontalAlignment(src, key));
  345. } else if (VERTICAL_ALIGNMENT.equals(key)) {
  346. dest.put(key, getVerticalAlignment(src, key));
  347. } else if (FILL_PATTERN.equals(key)) {
  348. dest.put(key, getFillPattern(src, key));
  349. } else {
  350. LOGGER.atInfo().log("Ignoring unrecognized CellUtil format properties key: {}", key);
  351. }
  352. }
  353. }
  354. /**
  355. * Sets the format properties of the given style based on the given map.
  356. *
  357. * @param style cell style
  358. * @param workbook parent workbook
  359. * @param properties map of format properties (String -> Object)
  360. * @see #getFormatProperties(CellStyle)
  361. */
  362. private static void setFormatProperties(CellStyle style, Workbook workbook, Map<String, Object> properties) {
  363. style.setAlignment(getHorizontalAlignment(properties, ALIGNMENT));
  364. style.setVerticalAlignment(getVerticalAlignment(properties, VERTICAL_ALIGNMENT));
  365. style.setBorderBottom(getBorderStyle(properties, BORDER_BOTTOM));
  366. style.setBorderLeft(getBorderStyle(properties, BORDER_LEFT));
  367. style.setBorderRight(getBorderStyle(properties, BORDER_RIGHT));
  368. style.setBorderTop(getBorderStyle(properties, BORDER_TOP));
  369. style.setBottomBorderColor(getShort(properties, BOTTOM_BORDER_COLOR));
  370. style.setDataFormat(getShort(properties, DATA_FORMAT));
  371. style.setFillPattern(getFillPattern(properties, FILL_PATTERN));
  372. style.setFillForegroundColor(getShort(properties, FILL_FOREGROUND_COLOR));
  373. style.setFillBackgroundColor(getShort(properties, FILL_BACKGROUND_COLOR));
  374. style.setFont(workbook.getFontAt(getInt(properties, FONT)));
  375. style.setHidden(getBoolean(properties, HIDDEN));
  376. style.setIndention(getShort(properties, INDENTION));
  377. style.setLeftBorderColor(getShort(properties, LEFT_BORDER_COLOR));
  378. style.setLocked(getBoolean(properties, LOCKED));
  379. style.setRightBorderColor(getShort(properties, RIGHT_BORDER_COLOR));
  380. style.setRotation(getShort(properties, ROTATION));
  381. style.setTopBorderColor(getShort(properties, TOP_BORDER_COLOR));
  382. style.setWrapText(getBoolean(properties, WRAP_TEXT));
  383. }
  384. /**
  385. * Utility method that returns the named short value from the given map.
  386. *
  387. * @param properties map of named properties (String -> Object)
  388. * @param name property name
  389. * @return zero if the property does not exist, or is not a {@link Short}
  390. * otherwise the property value
  391. */
  392. private static short getShort(Map<String, Object> properties, String name) {
  393. Object value = properties.get(name);
  394. if (value instanceof Number) {
  395. return ((Number) value).shortValue();
  396. }
  397. return 0;
  398. }
  399. /**
  400. * Utility method that returns the named int value from the given map.
  401. *
  402. * @param properties map of named properties (String -> Object)
  403. * @param name property name
  404. * @return zero if the property does not exist, or is not a {@link Integer}
  405. * otherwise the property value
  406. */
  407. private static int getInt(Map<String, Object> properties, String name) {
  408. Object value = properties.get(name);
  409. if (value instanceof Number) {
  410. return ((Number) value).intValue();
  411. }
  412. return 0;
  413. }
  414. /**
  415. * Utility method that returns the named BorderStyle value from the given map.
  416. *
  417. * @param properties map of named properties (String -> Object)
  418. * @param name property name
  419. * @return Border style if set, otherwise {@link BorderStyle#NONE}
  420. */
  421. private static BorderStyle getBorderStyle(Map<String, Object> properties, String name) {
  422. Object value = properties.get(name);
  423. BorderStyle border;
  424. if (value instanceof BorderStyle) {
  425. border = (BorderStyle) value;
  426. }
  427. // @deprecated 3.15 beta 2. getBorderStyle will only work on BorderStyle enums instead of codes in the future.
  428. else if (value instanceof Short) {
  429. LOGGER.atWarn().log("Deprecation warning: CellUtil properties map uses Short values for {}. Should use BorderStyle enums instead.", name);
  430. short code = ((Short) value).shortValue();
  431. border = BorderStyle.valueOf(code);
  432. }
  433. else if (value == null) {
  434. border = BorderStyle.NONE;
  435. }
  436. else {
  437. throw new RuntimeException("Unexpected border style class. Must be BorderStyle or Short (deprecated).");
  438. }
  439. return border;
  440. }
  441. /**
  442. * Utility method that returns the named FillPatternType value from the given map.
  443. *
  444. * @param properties map of named properties (String -> Object)
  445. * @param name property name
  446. * @return FillPatternType style if set, otherwise {@link FillPatternType#NO_FILL}
  447. * @since POI 3.15 beta 3
  448. */
  449. private static FillPatternType getFillPattern(Map<String, Object> properties, String name) {
  450. Object value = properties.get(name);
  451. FillPatternType pattern;
  452. if (value instanceof FillPatternType) {
  453. pattern = (FillPatternType) value;
  454. }
  455. // @deprecated 3.15 beta 2. getFillPattern will only work on FillPatternType enums instead of codes in the future.
  456. else if (value instanceof Short) {
  457. LOGGER.atWarn().log("Deprecation warning: CellUtil properties map uses Short values for {}. Should use FillPatternType enums instead.", name);
  458. short code = ((Short) value).shortValue();
  459. pattern = FillPatternType.forInt(code);
  460. }
  461. else if (value == null) {
  462. pattern = FillPatternType.NO_FILL;
  463. }
  464. else {
  465. throw new RuntimeException("Unexpected fill pattern style class. Must be FillPatternType or Short (deprecated).");
  466. }
  467. return pattern;
  468. }
  469. /**
  470. * Utility method that returns the named HorizontalAlignment value from the given map.
  471. *
  472. * @param properties map of named properties (String -> Object)
  473. * @param name property name
  474. * @return HorizontalAlignment style if set, otherwise {@link HorizontalAlignment#GENERAL}
  475. * @since POI 3.15 beta 3
  476. */
  477. private static HorizontalAlignment getHorizontalAlignment(Map<String, Object> properties, String name) {
  478. Object value = properties.get(name);
  479. HorizontalAlignment align;
  480. if (value instanceof HorizontalAlignment) {
  481. align = (HorizontalAlignment) value;
  482. }
  483. // @deprecated 3.15 beta 2. getHorizontalAlignment will only work on HorizontalAlignment enums instead of codes in the future.
  484. else if (value instanceof Short) {
  485. LOGGER.atWarn().log("Deprecation warning: CellUtil properties map used a Short value for {}. Should use HorizontalAlignment enums instead.", name);
  486. short code = ((Short) value).shortValue();
  487. align = HorizontalAlignment.forInt(code);
  488. }
  489. else if (value == null) {
  490. align = HorizontalAlignment.GENERAL;
  491. }
  492. else {
  493. throw new RuntimeException("Unexpected horizontal alignment style class. Must be HorizontalAlignment or Short (deprecated).");
  494. }
  495. return align;
  496. }
  497. /**
  498. * Utility method that returns the named VerticalAlignment value from the given map.
  499. *
  500. * @param properties map of named properties (String -> Object)
  501. * @param name property name
  502. * @return VerticalAlignment style if set, otherwise {@link VerticalAlignment#BOTTOM}
  503. * @since POI 3.15 beta 3
  504. */
  505. private static VerticalAlignment getVerticalAlignment(Map<String, Object> properties, String name) {
  506. Object value = properties.get(name);
  507. VerticalAlignment align;
  508. if (value instanceof VerticalAlignment) {
  509. align = (VerticalAlignment) value;
  510. }
  511. // @deprecated 3.15 beta 2. getVerticalAlignment will only work on VerticalAlignment enums instead of codes in the future.
  512. else if (value instanceof Short) {
  513. LOGGER.atWarn().log("Deprecation warning: CellUtil properties map used a Short value for {}. Should use VerticalAlignment enums instead.", name);
  514. short code = ((Short) value).shortValue();
  515. align = VerticalAlignment.forInt(code);
  516. }
  517. else if (value == null) {
  518. align = VerticalAlignment.BOTTOM;
  519. }
  520. else {
  521. throw new RuntimeException("Unexpected vertical alignment style class. Must be VerticalAlignment or Short (deprecated).");
  522. }
  523. return align;
  524. }
  525. /**
  526. * Utility method that returns the named boolean value from the given map.
  527. *
  528. * @param properties map of properties (String -> Object)
  529. * @param name property name
  530. * @return false if the property does not exist, or is not a {@link Boolean},
  531. * true otherwise
  532. */
  533. private static boolean getBoolean(Map<String, Object> properties, String name) {
  534. Object value = properties.get(name);
  535. //noinspection SimplifiableIfStatement
  536. if (value instanceof Boolean) {
  537. return ((Boolean) value).booleanValue();
  538. }
  539. return false;
  540. }
  541. /**
  542. * Utility method that puts the given value to the given map.
  543. *
  544. * @param properties map of properties (String -> Object)
  545. * @param name property name
  546. * @param value property value
  547. */
  548. private static void put(Map<String, Object> properties, String name, Object value) {
  549. properties.put(name, value);
  550. }
  551. /**
  552. * Looks for text in the cell that should be unicode, like &alpha; and provides the
  553. * unicode version of it.
  554. *
  555. *@param cell The cell to check for unicode values
  556. *@return translated to unicode
  557. */
  558. public static Cell translateUnicodeValues(Cell cell) {
  559. String s = cell.getRichStringCellValue().getString();
  560. boolean foundUnicode = false;
  561. String lowerCaseStr = s.toLowerCase(Locale.ROOT);
  562. for (UnicodeMapping entry : unicodeMappings) {
  563. String key = entry.entityName;
  564. if (lowerCaseStr.contains(key)) {
  565. s = s.replaceAll(key, entry.resolvedValue);
  566. foundUnicode = true;
  567. }
  568. }
  569. if (foundUnicode) {
  570. cell.setCellValue(cell.getRow().getSheet().getWorkbook().getCreationHelper()
  571. .createRichTextString(s));
  572. }
  573. return cell;
  574. }
  575. static {
  576. unicodeMappings = new UnicodeMapping[] {
  577. um("alpha", "\u03B1" ),
  578. um("beta", "\u03B2" ),
  579. um("gamma", "\u03B3" ),
  580. um("delta", "\u03B4" ),
  581. um("epsilon", "\u03B5" ),
  582. um("zeta", "\u03B6" ),
  583. um("eta", "\u03B7" ),
  584. um("theta", "\u03B8" ),
  585. um("iota", "\u03B9" ),
  586. um("kappa", "\u03BA" ),
  587. um("lambda", "\u03BB" ),
  588. um("mu", "\u03BC" ),
  589. um("nu", "\u03BD" ),
  590. um("xi", "\u03BE" ),
  591. um("omicron", "\u03BF" ),
  592. };
  593. }
  594. private static UnicodeMapping um(String entityName, String resolvedValue) {
  595. return new UnicodeMapping(entityName, resolvedValue);
  596. }
  597. }