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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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.Collections;
  17. import java.util.HashMap;
  18. import java.util.Locale;
  19. import java.util.Map;
  20. import org.apache.poi.ss.usermodel.BorderStyle;
  21. import org.apache.poi.ss.usermodel.Cell;
  22. import org.apache.poi.ss.usermodel.CellStyle;
  23. import org.apache.poi.ss.usermodel.Font;
  24. import org.apache.poi.ss.usermodel.Row;
  25. import org.apache.poi.ss.usermodel.Sheet;
  26. import org.apache.poi.ss.usermodel.Workbook;
  27. /**
  28. * Various utility functions that make working with a cells and rows easier. The various methods
  29. * that deal with style's allow you to create your CellStyles as you need them. When you apply a
  30. * style change to a cell, the code will attempt to see if a style already exists that meets your
  31. * needs. If not, then it will create a new style. This is to prevent creating too many styles.
  32. * there is an upper limit in Excel on the number of styles that can be supported.
  33. *
  34. *@author Eric Pugh epugh@upstate.com
  35. *@author (secondary) Avinash Kewalramani akewalramani@accelrys.com
  36. */
  37. public final class CellUtil {
  38. public static final String ALIGNMENT = "alignment";
  39. public static final String BORDER_BOTTOM = "borderBottom";
  40. public static final String BORDER_LEFT = "borderLeft";
  41. public static final String BORDER_RIGHT = "borderRight";
  42. public static final String BORDER_TOP = "borderTop";
  43. public static final String BOTTOM_BORDER_COLOR = "bottomBorderColor";
  44. public static final String DATA_FORMAT = "dataFormat";
  45. public static final String FILL_BACKGROUND_COLOR = "fillBackgroundColor";
  46. public static final String FILL_FOREGROUND_COLOR = "fillForegroundColor";
  47. public static final String FILL_PATTERN = "fillPattern";
  48. public static final String FONT = "font";
  49. public static final String HIDDEN = "hidden";
  50. public static final String INDENTION = "indention";
  51. public static final String LEFT_BORDER_COLOR = "leftBorderColor";
  52. public static final String LOCKED = "locked";
  53. public static final String RIGHT_BORDER_COLOR = "rightBorderColor";
  54. public static final String ROTATION = "rotation";
  55. public static final String TOP_BORDER_COLOR = "topBorderColor";
  56. public static final String VERTICAL_ALIGNMENT = "verticalAlignment";
  57. public static final String WRAP_TEXT = "wrapText";
  58. private static UnicodeMapping unicodeMappings[];
  59. private static final class UnicodeMapping {
  60. public final String entityName;
  61. public final String resolvedValue;
  62. public UnicodeMapping(String pEntityName, String pResolvedValue) {
  63. entityName = "&" + pEntityName + ";";
  64. resolvedValue = pResolvedValue;
  65. }
  66. }
  67. private CellUtil() {
  68. // no instances of this class
  69. }
  70. /**
  71. * Get a row from the spreadsheet, and create it if it doesn't exist.
  72. *
  73. *@param rowIndex The 0 based row number
  74. *@param sheet The sheet that the row is part of.
  75. *@return The row indicated by the rowCounter
  76. */
  77. public static Row getRow(int rowIndex, Sheet sheet) {
  78. Row row = sheet.getRow(rowIndex);
  79. if (row == null) {
  80. row = sheet.createRow(rowIndex);
  81. }
  82. return row;
  83. }
  84. /**
  85. * Get a specific cell from a row. If the cell doesn't exist, then create it.
  86. *
  87. *@param row The row that the cell is part of
  88. *@param columnIndex The column index that the cell is in.
  89. *@return The cell indicated by the column.
  90. */
  91. public static Cell getCell(Row row, int columnIndex) {
  92. Cell cell = row.getCell(columnIndex);
  93. if (cell == null) {
  94. cell = row.createCell(columnIndex);
  95. }
  96. return cell;
  97. }
  98. /**
  99. * Creates a cell, gives it a value, and applies a style if provided
  100. *
  101. * @param row the row to create the cell in
  102. * @param column the column index to create the cell in
  103. * @param value The value of the cell
  104. * @param style If the style is not null, then set
  105. * @return A new Cell
  106. */
  107. public static Cell createCell(Row row, int column, String value, CellStyle style) {
  108. Cell cell = getCell(row, column);
  109. cell.setCellValue(cell.getRow().getSheet().getWorkbook().getCreationHelper()
  110. .createRichTextString(value));
  111. if (style != null) {
  112. cell.setCellStyle(style);
  113. }
  114. return cell;
  115. }
  116. /**
  117. * Create a cell, and give it a value.
  118. *
  119. *@param row the row to create the cell in
  120. *@param column the column index to create the cell in
  121. *@param value The value of the cell
  122. *@return A new Cell.
  123. */
  124. public static Cell createCell(Row row, int column, String value) {
  125. return createCell(row, column, value, null);
  126. }
  127. /**
  128. * Take a cell, and align it.
  129. *
  130. *@param cell the cell to set the alignment for
  131. *@param workbook The workbook that is being worked with.
  132. *@param align the column alignment to use.
  133. *
  134. * @see CellStyle for alignment options
  135. */
  136. public static void setAlignment(Cell cell, Workbook workbook, short align) {
  137. setCellStyleProperty(cell, workbook, ALIGNMENT, Short.valueOf(align));
  138. }
  139. /**
  140. * Take a cell, and apply a font to it
  141. *
  142. *@param cell the cell to set the alignment for
  143. *@param workbook The workbook that is being worked with.
  144. *@param font The Font that you want to set...
  145. */
  146. public static void setFont(Cell cell, Workbook workbook, Font font) {
  147. // Check if font belongs to workbook
  148. final short fontIndex = font.getIndex();
  149. if (!workbook.getFontAt(fontIndex).equals(font)) {
  150. throw new IllegalArgumentException("Font does not belong to this workbook");
  151. }
  152. // Check if cell belongs to workbook
  153. // (checked in setCellStyleProperty)
  154. setCellStyleProperty(cell, workbook, FONT, fontIndex);
  155. }
  156. /**
  157. * <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
  158. * current style plus styles properties in <code>properties</code>. A new style is created if the
  159. * workbook does not contain a matching style.</p>
  160. *
  161. * <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
  162. * same style.</p>
  163. *
  164. * <p>This is necessary because Excel has an upper limit on the number of styles that it supports.</p>
  165. *
  166. * <p>This function is more efficient than multiple calls to
  167. * {@link #setCellStyleProperty(org.apache.poi.ss.usermodel.Cell, org.apache.poi.ss.usermodel.Workbook, String, Object)}
  168. * if adding multiple cell styles.</p>
  169. *
  170. * <p>For performance reasons, if this is the only cell in a workbook that uses a cell style,
  171. * this method does NOT remove the old style from the workbook.
  172. * <!-- NOT IMPLEMENTED: Unused styles should be
  173. * pruned from the workbook with [@link #removeUnusedCellStyles(Workbook)] or
  174. * [@link #removeStyleFromWorkbookIfUnused(CellStyle, Workbook)]. -->
  175. * </p>
  176. *
  177. * @param cell The cell to change the style of
  178. * @param properties The properties to be added to a cell style, as {propertyName: propertyValue}.
  179. * @since POI 3.14 beta 2
  180. */
  181. public static void setCellStyleProperties(Cell cell, Map<String, Object> properties) {
  182. @SuppressWarnings("resource")
  183. Workbook workbook = cell.getSheet().getWorkbook();
  184. CellStyle originalStyle = cell.getCellStyle();
  185. CellStyle newStyle = null;
  186. Map<String, Object> values = getFormatProperties(originalStyle);
  187. values.putAll(properties);
  188. // index seems like what index the cellstyle is in the list of styles for a workbook.
  189. // not good to compare on!
  190. int numberCellStyles = workbook.getNumCellStyles();
  191. for (int i = 0; i < numberCellStyles; i++) {
  192. CellStyle wbStyle = workbook.getCellStyleAt(i);
  193. Map<String, Object> wbStyleMap = getFormatProperties(wbStyle);
  194. // the desired style already exists in the workbook. Use the existing style.
  195. if (wbStyleMap.equals(values)) {
  196. newStyle = wbStyle;
  197. break;
  198. }
  199. }
  200. // the desired style does not exist in the workbook. Create a new style with desired properties.
  201. if (newStyle == null) {
  202. newStyle = workbook.createCellStyle();
  203. setFormatProperties(newStyle, workbook, values);
  204. }
  205. cell.setCellStyle(newStyle);
  206. }
  207. /**
  208. * <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
  209. * current style plus a single style property <code>propertyName</code> with value
  210. * <code>propertyValue<code>.
  211. * A new style is created if the workbook does not contain a matching style.</p>
  212. *
  213. * <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
  214. * same style.</p>
  215. *
  216. * <p>If setting more than one cell style property on a cell, use
  217. * {@link #setCellStyleProperties(org.apache.poi.ss.usermodel.Cell, Map)},
  218. * which is faster and does not add unnecessary intermediate CellStyles to the workbook.</p>
  219. *
  220. * @param workbook The workbook that is being worked with.
  221. * @param propertyName The name of the property that is to be changed.
  222. * @param propertyValue The value of the property that is to be changed.
  223. * @param cell The cell that needs it's style changes
  224. */
  225. public static void setCellStyleProperty(Cell cell, Workbook workbook, String propertyName,
  226. Object propertyValue) {
  227. if (cell.getSheet().getWorkbook() != workbook) {
  228. throw new IllegalArgumentException("Cannot set cell style property. Cell does not belong to workbook.");
  229. }
  230. Map<String, Object> values = Collections.singletonMap(propertyName, propertyValue);
  231. setCellStyleProperties(cell, values);
  232. }
  233. /**
  234. * Returns a map containing the format properties of the given cell style.
  235. * The returned map is not tied to <code>style</code>, so subsequent changes
  236. * to <code>style</code> will not modify the map, and changes to the returned
  237. * map will not modify the cell style. The returned map is mutable.
  238. *
  239. * @param style cell style
  240. * @return map of format properties (String -> Object)
  241. * @see #setFormatProperties(org.apache.poi.ss.usermodel.CellStyle, org.apache.poi.ss.usermodel.Workbook, java.util.Map)
  242. */
  243. private static Map<String, Object> getFormatProperties(CellStyle style) {
  244. Map<String, Object> properties = new HashMap<String, Object>();
  245. putShort(properties, ALIGNMENT, style.getAlignment());
  246. putBorderStyle(properties, BORDER_BOTTOM, style.getBorderBottom());
  247. putBorderStyle(properties, BORDER_LEFT, style.getBorderLeft());
  248. putBorderStyle(properties, BORDER_RIGHT, style.getBorderRight());
  249. putBorderStyle(properties, BORDER_TOP, style.getBorderTop());
  250. putShort(properties, BOTTOM_BORDER_COLOR, style.getBottomBorderColor());
  251. putShort(properties, DATA_FORMAT, style.getDataFormat());
  252. putShort(properties, FILL_BACKGROUND_COLOR, style.getFillBackgroundColor());
  253. putShort(properties, FILL_FOREGROUND_COLOR, style.getFillForegroundColor());
  254. putShort(properties, FILL_PATTERN, style.getFillPattern());
  255. putShort(properties, FONT, style.getFontIndex());
  256. putBoolean(properties, HIDDEN, style.getHidden());
  257. putShort(properties, INDENTION, style.getIndention());
  258. putShort(properties, LEFT_BORDER_COLOR, style.getLeftBorderColor());
  259. putBoolean(properties, LOCKED, style.getLocked());
  260. putShort(properties, RIGHT_BORDER_COLOR, style.getRightBorderColor());
  261. putShort(properties, ROTATION, style.getRotation());
  262. putShort(properties, TOP_BORDER_COLOR, style.getTopBorderColor());
  263. putShort(properties, VERTICAL_ALIGNMENT, style.getVerticalAlignment());
  264. putBoolean(properties, WRAP_TEXT, style.getWrapText());
  265. return properties;
  266. }
  267. /**
  268. * Sets the format properties of the given style based on the given map.
  269. *
  270. * @param style cell style
  271. * @param workbook parent workbook
  272. * @param properties map of format properties (String -> Object)
  273. * @see #getFormatProperties(CellStyle)
  274. */
  275. private static void setFormatProperties(CellStyle style, Workbook workbook, Map<String, Object> properties) {
  276. style.setAlignment(getShort(properties, ALIGNMENT));
  277. style.setBorderBottom(getBorderStyle(properties, BORDER_BOTTOM));
  278. style.setBorderLeft(getBorderStyle(properties, BORDER_LEFT));
  279. style.setBorderRight(getBorderStyle(properties, BORDER_RIGHT));
  280. style.setBorderTop(getBorderStyle(properties, BORDER_TOP));
  281. style.setBottomBorderColor(getShort(properties, BOTTOM_BORDER_COLOR));
  282. style.setDataFormat(getShort(properties, DATA_FORMAT));
  283. style.setFillBackgroundColor(getShort(properties, FILL_BACKGROUND_COLOR));
  284. style.setFillForegroundColor(getShort(properties, FILL_FOREGROUND_COLOR));
  285. style.setFillPattern(getShort(properties, FILL_PATTERN));
  286. style.setFont(workbook.getFontAt(getShort(properties, FONT)));
  287. style.setHidden(getBoolean(properties, HIDDEN));
  288. style.setIndention(getShort(properties, INDENTION));
  289. style.setLeftBorderColor(getShort(properties, LEFT_BORDER_COLOR));
  290. style.setLocked(getBoolean(properties, LOCKED));
  291. style.setRightBorderColor(getShort(properties, RIGHT_BORDER_COLOR));
  292. style.setRotation(getShort(properties, ROTATION));
  293. style.setTopBorderColor(getShort(properties, TOP_BORDER_COLOR));
  294. style.setVerticalAlignment(getShort(properties, VERTICAL_ALIGNMENT));
  295. style.setWrapText(getBoolean(properties, WRAP_TEXT));
  296. }
  297. /**
  298. * Utility method that returns the named short value form the given map.
  299. *
  300. * @param properties map of named properties (String -> Object)
  301. * @param name property name
  302. * @return zero if the property does not exist, or is not a {@link Short}
  303. * otherwise the property value
  304. */
  305. private static short getShort(Map<String, Object> properties, String name) {
  306. Object value = properties.get(name);
  307. if (value instanceof Short) {
  308. return ((Short) value).shortValue();
  309. }
  310. return 0;
  311. }
  312. /**
  313. * Utility method that returns the named BorderStyle value form the given map.
  314. *
  315. * @param properties map of named properties (String -> Object)
  316. * @param name property name
  317. * @return Border style if set, otherwise {@link BorderStyle#NONE}
  318. */
  319. private static BorderStyle getBorderStyle(Map<String, Object> properties, String name) {
  320. BorderStyle value = (BorderStyle) properties.get(name);
  321. return (value != null) ? value : BorderStyle.NONE;
  322. }
  323. /**
  324. * Utility method that returns the named boolean value form the given map.
  325. *
  326. * @param properties map of properties (String -> Object)
  327. * @param name property name
  328. * @return false if the property does not exist, or is not a {@link Boolean},
  329. * true otherwise
  330. */
  331. private static boolean getBoolean(Map<String, Object> properties, String name) {
  332. Object value = properties.get(name);
  333. //noinspection SimplifiableIfStatement
  334. if (value instanceof Boolean) {
  335. return ((Boolean) value).booleanValue();
  336. }
  337. return false;
  338. }
  339. /**
  340. * Utility method that puts the named short value to the given map.
  341. *
  342. * @param properties map of properties (String -> Object)
  343. * @param name property name
  344. * @param value property value
  345. */
  346. private static void putShort(Map<String, Object> properties, String name, short value) {
  347. properties.put(name, Short.valueOf(value));
  348. }
  349. /**
  350. * Utility method that puts the named short value to the given map.
  351. *
  352. * @param properties map of properties (String -> Object)
  353. * @param name property name
  354. * @param value property value
  355. */
  356. private static void putBorderStyle(Map<String, Object> properties, String name, BorderStyle border) {
  357. properties.put(name, border);
  358. }
  359. /**
  360. * Utility method that puts the named boolean value to the given map.
  361. *
  362. * @param properties map of properties (String -> Object)
  363. * @param name property name
  364. * @param value property value
  365. */
  366. private static void putBoolean(Map<String, Object> properties, String name, boolean value) {
  367. properties.put(name, Boolean.valueOf(value));
  368. }
  369. /**
  370. * Looks for text in the cell that should be unicode, like &alpha; and provides the
  371. * unicode version of it.
  372. *
  373. *@param cell The cell to check for unicode values
  374. *@return translated to unicode
  375. */
  376. public static Cell translateUnicodeValues(Cell cell) {
  377. String s = cell.getRichStringCellValue().getString();
  378. boolean foundUnicode = false;
  379. String lowerCaseStr = s.toLowerCase(Locale.ROOT);
  380. for (UnicodeMapping entry : unicodeMappings) {
  381. String key = entry.entityName;
  382. if (lowerCaseStr.contains(key)) {
  383. s = s.replaceAll(key, entry.resolvedValue);
  384. foundUnicode = true;
  385. }
  386. }
  387. if (foundUnicode) {
  388. cell.setCellValue(cell.getRow().getSheet().getWorkbook().getCreationHelper()
  389. .createRichTextString(s));
  390. }
  391. return cell;
  392. }
  393. static {
  394. unicodeMappings = new UnicodeMapping[] {
  395. um("alpha", "\u03B1" ),
  396. um("beta", "\u03B2" ),
  397. um("gamma", "\u03B3" ),
  398. um("delta", "\u03B4" ),
  399. um("epsilon", "\u03B5" ),
  400. um("zeta", "\u03B6" ),
  401. um("eta", "\u03B7" ),
  402. um("theta", "\u03B8" ),
  403. um("iota", "\u03B9" ),
  404. um("kappa", "\u03BA" ),
  405. um("lambda", "\u03BB" ),
  406. um("mu", "\u03BC" ),
  407. um("nu", "\u03BD" ),
  408. um("xi", "\u03BE" ),
  409. um("omicron", "\u03BF" ),
  410. };
  411. }
  412. private static UnicodeMapping um(String entityName, String resolvedValue) {
  413. return new UnicodeMapping(entityName, resolvedValue);
  414. }
  415. }