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 31KB

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