Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SheetUtil.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.awt.font.FontRenderContext;
  17. import java.awt.font.TextAttribute;
  18. import java.awt.font.TextLayout;
  19. import java.awt.geom.AffineTransform;
  20. import java.awt.geom.Rectangle2D;
  21. import java.text.AttributedString;
  22. import java.util.List;
  23. import java.util.Locale;
  24. import java.util.Map;
  25. import org.apache.poi.ss.usermodel.Cell;
  26. import org.apache.poi.ss.usermodel.CellStyle;
  27. import org.apache.poi.ss.usermodel.CellType;
  28. import org.apache.poi.ss.usermodel.CellValue;
  29. import org.apache.poi.ss.usermodel.DataFormatter;
  30. import org.apache.poi.ss.usermodel.Font;
  31. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  32. import org.apache.poi.ss.usermodel.RichTextString;
  33. import org.apache.poi.ss.usermodel.Row;
  34. import org.apache.poi.ss.usermodel.Sheet;
  35. import org.apache.poi.ss.usermodel.Workbook;
  36. import org.apache.poi.util.Internal;
  37. /**
  38. * Helper methods for when working with Usermodel sheets
  39. */
  40. public class SheetUtil {
  41. /**
  42. * Excel measures columns in units of 1/256th of a character width
  43. * but the docs say nothing about what particular character is used.
  44. * '0' looks to be a good choice.
  45. */
  46. private static final char defaultChar = '0';
  47. /**
  48. * This is the multiple that the font height is scaled by when determining the
  49. * boundary of rotated text.
  50. */
  51. private static final double fontHeightMultiple = 2.0;
  52. /**
  53. * Dummy formula evaluator that does nothing.
  54. * YK: The only reason of having this class is that
  55. * {@link org.apache.poi.ss.usermodel.DataFormatter#formatCellValue(org.apache.poi.ss.usermodel.Cell)}
  56. * returns formula string for formula cells. Dummy evaluator makes it to format the cached formula result.
  57. *
  58. * See Bugzilla #50021
  59. */
  60. private static final FormulaEvaluator dummyEvaluator = new FormulaEvaluator() {
  61. @Override
  62. public void clearAllCachedResultValues(){}
  63. @Override
  64. public void notifySetFormula(Cell cell) {}
  65. @Override
  66. public void notifyDeleteCell(Cell cell) {}
  67. @Override
  68. public void notifyUpdateCell(Cell cell) {}
  69. @Override
  70. public CellValue evaluate(Cell cell) {return null; }
  71. @Override
  72. public Cell evaluateInCell(Cell cell) { return null; }
  73. @Override
  74. public void setupReferencedWorkbooks(Map<String, FormulaEvaluator> workbooks) {}
  75. @Override
  76. public void setDebugEvaluationOutputForNextEval(boolean value) {}
  77. @Override
  78. public void setIgnoreMissingWorkbooks(boolean ignore) {}
  79. @Override
  80. public void evaluateAll() {}
  81. @Override
  82. public CellType evaluateFormulaCell(Cell cell) { return cell.getCachedFormulaResultType(); }
  83. };
  84. /**
  85. * drawing context to measure text
  86. */
  87. private static final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true);
  88. /**
  89. * A system property which can be enabled to not fail when the
  90. * font-system is not available on the current machine
  91. */
  92. private static final boolean ignoreMissingFontSystem =
  93. Boolean.parseBoolean(System.getProperty("org.apache.poi.ss.ignoreMissingFontSystem"));
  94. /**
  95. * Which default char-width to use if the font-system is unavailable.
  96. */
  97. public static final int DEFAULT_CHAR_WIDTH = 5;
  98. /**
  99. * Compute width of a single cell
  100. *
  101. * @param cell the cell whose width is to be calculated
  102. * @param defaultCharWidth the width of a single character
  103. * @param formatter formatter used to prepare the text to be measured
  104. * @param useMergedCells whether to use merged cells
  105. * @return the width in pixels or -1 if cell is empty
  106. * @deprecated since POI 5.2.5, it is better to pass defaultCharWidth as a float
  107. */
  108. public static double getCellWidth(Cell cell, int defaultCharWidth, DataFormatter formatter, boolean useMergedCells) {
  109. return getCellWidth(cell, (float) defaultCharWidth, formatter, useMergedCells);
  110. }
  111. /**
  112. * Compute width of a single cell
  113. *
  114. * @param cell the cell whose width is to be calculated
  115. * @param defaultCharWidth the width of a single character
  116. * @param formatter formatter used to prepare the text to be measured
  117. * @param useMergedCells whether to use merged cells
  118. * @return the width in pixels or -1 if cell is empty
  119. * @since POI 5.2.5
  120. */
  121. public static double getCellWidth(Cell cell, float defaultCharWidth, DataFormatter formatter, boolean useMergedCells) {
  122. List<CellRangeAddress> mergedRegions = cell.getSheet().getMergedRegions();
  123. return getCellWidth(cell, defaultCharWidth, formatter, useMergedCells, mergedRegions);
  124. }
  125. /**
  126. * Compute width of a single cell
  127. *
  128. * This method receives the list of merged regions as querying it from the cell/sheet
  129. * is time-consuming and thus caching the list across cells speeds up certain operations
  130. * considerably.
  131. *
  132. * @param cell the cell whose width is to be calculated
  133. * @param defaultCharWidth the width of a single character
  134. * @param formatter formatter used to prepare the text to be measured
  135. * @param useMergedCells whether to use merged cells
  136. * @param mergedRegions The list of merged regions as received via cell.getSheet().getMergedRegions()
  137. * @return the width in pixels or -1 if cell is empty
  138. * @deprecated since POI 5.2.5, it is better to pass defaultCharWidth as a float
  139. */
  140. public static double getCellWidth(Cell cell, int defaultCharWidth, DataFormatter formatter, boolean useMergedCells,
  141. List<CellRangeAddress> mergedRegions) {
  142. return getCellWidth(cell, (float) defaultCharWidth, formatter, useMergedCells, mergedRegions);
  143. }
  144. /**
  145. * Compute width of a single cell
  146. *
  147. * This method receives the list of merged regions as querying it from the cell/sheet
  148. * is time-consuming and thus caching the list across cells speeds up certain operations
  149. * considerably.
  150. *
  151. * @param cell the cell whose width is to be calculated
  152. * @param defaultCharWidth the width of a single character
  153. * @param formatter formatter used to prepare the text to be measured
  154. * @param useMergedCells whether to use merged cells
  155. * @param mergedRegions The list of merged regions as received via cell.getSheet().getMergedRegions()
  156. * @return the width in pixels or -1 if cell is empty
  157. * @since POI 5.2.5
  158. */
  159. public static double getCellWidth(Cell cell, float defaultCharWidth, DataFormatter formatter, boolean useMergedCells,
  160. List<CellRangeAddress> mergedRegions) {
  161. Sheet sheet = cell.getSheet();
  162. Workbook wb = sheet.getWorkbook();
  163. Row row = cell.getRow();
  164. int column = cell.getColumnIndex();
  165. // FIXME: this looks very similar to getCellWithMerges below. Consider consolidating.
  166. // We should only be checking merged regions if useMergedCells is true. Why are we doing this for-loop?
  167. int colspan = 1;
  168. for (CellRangeAddress region : mergedRegions) {
  169. if (region.isInRange(row.getRowNum(), column)) {
  170. if (!useMergedCells) {
  171. // If we're not using merged cells, skip this one and move on to the next.
  172. return -1;
  173. }
  174. cell = row.getCell(region.getFirstColumn());
  175. colspan = 1 + region.getLastColumn() - region.getFirstColumn();
  176. }
  177. }
  178. CellStyle style = cell.getCellStyle();
  179. CellType cellType = cell.getCellType();
  180. // for formula cells we compute the cell width for the cached formula result
  181. if (cellType == CellType.FORMULA)
  182. cellType = cell.getCachedFormulaResultType();
  183. Font font = wb.getFontAt(style.getFontIndex());
  184. double width = -1;
  185. if (cellType == CellType.STRING) {
  186. RichTextString rt = cell.getRichStringCellValue();
  187. if (rt != null && rt.getString() != null) {
  188. String[] lines = rt.getString().split("\\n");
  189. for (String line : lines) {
  190. String txt = line + defaultChar;
  191. AttributedString str = new AttributedString(txt);
  192. copyAttributes(font, str, 0, txt.length());
  193. /*if (rt.numFormattingRuns() > 0) {
  194. // TODO: support rich text fragments
  195. }*/
  196. width = getCellWidth(defaultCharWidth, colspan, style, width, str);
  197. }
  198. }
  199. } else {
  200. String sval = null;
  201. if (cellType == CellType.NUMERIC) {
  202. // Try to get it formatted to look the same as excel
  203. try {
  204. sval = formatter.formatCellValue(cell, dummyEvaluator);
  205. } catch (Exception e) {
  206. sval = String.valueOf(cell.getNumericCellValue());
  207. }
  208. } else if (cellType == CellType.BOOLEAN) {
  209. sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase(Locale.ROOT);
  210. }
  211. if(sval != null) {
  212. String txt = sval + defaultChar;
  213. AttributedString str = new AttributedString(txt);
  214. copyAttributes(font, str, 0, txt.length());
  215. width = getCellWidth(defaultCharWidth, colspan, style, width, str);
  216. }
  217. }
  218. return width;
  219. }
  220. /**
  221. * Calculate the best-fit width for a cell
  222. * If a merged cell spans multiple columns, evenly distribute the column width among those columns
  223. *
  224. * @param defaultCharWidth the width of a character using the default font in a workbook
  225. * @param colspan the number of columns that is spanned by the cell (1 if the cell is not part of a merged region)
  226. * @param style the cell style, which contains text rotation and indention information needed to compute the cell width
  227. * @param minWidth the minimum best-fit width. This algorithm will only return values greater than or equal to the minimum width.
  228. * @param str the text contained in the cell
  229. * @return the best fit cell width
  230. */
  231. private static double getCellWidth(float defaultCharWidth, int colspan,
  232. CellStyle style, double minWidth, AttributedString str) {
  233. TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext);
  234. final Rectangle2D bounds;
  235. if (style.getRotation() != 0) {
  236. /*
  237. * Transform the text using a scale so that its height is increased by a multiple of the leading,
  238. * and then rotate the text before computing the bounds. The scale results in some whitespace around
  239. * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
  240. * is added by the standard Excel autosize.
  241. */
  242. AffineTransform trans = new AffineTransform();
  243. trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
  244. trans.concatenate(
  245. AffineTransform.getScaleInstance(1, fontHeightMultiple)
  246. );
  247. bounds = layout.getOutline(trans).getBounds();
  248. } else {
  249. bounds = layout.getBounds();
  250. }
  251. // frameWidth accounts for leading spaces which is excluded from bounds.getWidth()
  252. final double frameWidth = bounds.getX() + bounds.getWidth();
  253. return Math.max(minWidth, ((frameWidth / colspan) / defaultCharWidth) + style.getIndention());
  254. }
  255. /**
  256. * Compute width of a column and return the result.
  257. * Note that this fall can fail if you do not have the right fonts installed in your OS.
  258. *
  259. * @param sheet the sheet to calculate
  260. * @param column 0-based index of the column
  261. * @param useMergedCells whether to use merged cells
  262. * @return the width in pixels or -1 if all cells are empty
  263. */
  264. public static double getColumnWidth(Sheet sheet, int column, boolean useMergedCells) {
  265. return getColumnWidth(sheet, column, useMergedCells, sheet.getFirstRowNum(), sheet.getLastRowNum());
  266. }
  267. /**
  268. * Compute width of a column based on a subset of the rows and return the result.
  269. * Note that this fall can fail if you do not have the right fonts installed in your OS.
  270. *
  271. * @param sheet the sheet to calculate
  272. * @param column 0-based index of the column
  273. * @param useMergedCells whether to use merged cells
  274. * @param firstRow 0-based index of the first row to consider (inclusive)
  275. * @param lastRow 0-based index of the last row to consider (inclusive)
  276. * @return the width in pixels or -1 if cell is empty
  277. */
  278. public static double getColumnWidth(Sheet sheet, int column, boolean useMergedCells, int firstRow, int lastRow){
  279. DataFormatter formatter = new DataFormatter();
  280. float defaultCharWidth = getDefaultCharWidthAsFloat(sheet.getWorkbook());
  281. List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
  282. double width = -1;
  283. for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx) {
  284. Row row = sheet.getRow(rowIdx);
  285. if( row != null ) {
  286. double cellWidth = getColumnWidthForRow(row, column, defaultCharWidth, formatter, useMergedCells, mergedRegions);
  287. width = Math.max(width, cellWidth);
  288. }
  289. }
  290. return width;
  291. }
  292. /**
  293. * Get default character width using the Workbook's default font. Note that this can
  294. * fail if your OS does not have the right fonts installed.
  295. *
  296. * @param wb the workbook to get the default character width from
  297. * @return default character width in pixels
  298. * @deprecated since POI 5.2.5, it is recommended to switch to {@link #getDefaultCharWidthAsFloat(Workbook)}.
  299. */
  300. @Internal
  301. public static int getDefaultCharWidth(final Workbook wb) {
  302. return Math.round(getDefaultCharWidthAsFloat(wb));
  303. }
  304. /**
  305. * Get default character width using the Workbook's default font. Note that this can
  306. * fail if your OS does not have the right fonts installed.
  307. *
  308. * @param wb the workbook to get the default character width from
  309. * @return default character width in pixels (as a float)
  310. * @since POI 5.2.5
  311. */
  312. @Internal
  313. public static float getDefaultCharWidthAsFloat(final Workbook wb) {
  314. Font defaultFont = wb.getFontAt( 0);
  315. AttributedString str = new AttributedString(String.valueOf(defaultChar));
  316. copyAttributes(defaultFont, str, 0, 1);
  317. try {
  318. TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext);
  319. return layout.getAdvance();
  320. } catch (UnsatisfiedLinkError | NoClassDefFoundError | InternalError e) {
  321. if (ignoreMissingFontSystem) {
  322. return DEFAULT_CHAR_WIDTH;
  323. }
  324. throw e;
  325. }
  326. }
  327. /**
  328. * Compute width of a single cell in a row
  329. * Convenience method for {@link #getCellWidth}
  330. *
  331. * @param row the row that contains the cell of interest
  332. * @param column the column number of the cell whose width is to be calculated
  333. * @param defaultCharWidth the width of a single character
  334. * @param formatter formatter used to prepare the text to be measured
  335. * @param useMergedCells whether to use merged cells
  336. * @return the width in pixels or -1 if cell is empty
  337. */
  338. private static double getColumnWidthForRow(
  339. Row row, int column, float defaultCharWidth, DataFormatter formatter, boolean useMergedCells,
  340. List<CellRangeAddress> mergedRegions) {
  341. if( row == null ) {
  342. return -1;
  343. }
  344. Cell cell = row.getCell(column);
  345. if (cell == null) {
  346. return -1;
  347. }
  348. return getCellWidth(cell, defaultCharWidth, formatter, useMergedCells, mergedRegions);
  349. }
  350. /**
  351. * Check if the Fonts are installed correctly so that Java can compute the size of
  352. * columns.
  353. *
  354. * If a Cell uses a Font which is not available on the operating system then Java may
  355. * fail to return useful Font metrics and thus lead to an auto-computed size of 0.
  356. *
  357. * This method allows to check if computing the sizes for a given Font will succeed or not.
  358. *
  359. * @param font The Font that is used in the Cell
  360. * @return true if computing the size for this Font will succeed, false otherwise
  361. */
  362. public static boolean canComputeColumnWidth(Font font) {
  363. // not sure what is the best value sample-here, only "1" did not work on some platforms...
  364. AttributedString str = new AttributedString("1w");
  365. copyAttributes(font, str, 0, "1w".length());
  366. TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext);
  367. return (layout.getBounds().getWidth() > 0);
  368. }
  369. /**
  370. * Copy text attributes from the supplied Font to Java2D AttributedString
  371. */
  372. private static void copyAttributes(Font font, AttributedString str, @SuppressWarnings("SameParameterValue") int startIdx, int endIdx) {
  373. str.addAttribute(TextAttribute.FAMILY, font.getFontName(), startIdx, endIdx);
  374. str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints());
  375. if (font.getBold()) str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
  376. if (font.getItalic() ) str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
  377. if (font.getUnderline() == Font.U_SINGLE ) str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
  378. }
  379. /**
  380. * Return the cell, without taking account of merged regions.
  381. * <p>
  382. * Use {@link #getCellWithMerges(Sheet, int, int)} if you want the top left
  383. * cell from merged regions instead when the reference is a merged cell.
  384. * <p>
  385. * Use this where you want to know if the given cell is explicitly defined
  386. * or not.
  387. *
  388. * @param sheet The workbook sheet to look at.
  389. * @param rowIx The 0-based index of the row.
  390. * @param colIx The 0-based index of the cell.
  391. * @return cell at the given location, or null if not defined
  392. * @throws NullPointerException if sheet is null
  393. */
  394. public static Cell getCell(Sheet sheet, int rowIx, int colIx) {
  395. Row r = sheet.getRow(rowIx);
  396. if (r != null) {
  397. return r.getCell(colIx);
  398. }
  399. return null;
  400. }
  401. /**
  402. * Return the cell, taking account of merged regions. Allows you to find the
  403. * cell who's contents are shown in a given position in the sheet.
  404. *
  405. * <p>If the cell at the given co-ordinates is a merged cell, this will
  406. * return the primary (top-left) most cell of the merged region.
  407. * <p>If the cell at the given co-ordinates is not in a merged region,
  408. * then will return the cell itself.
  409. * <p>If there is no cell defined at the given co-ordinates, will return
  410. * null.
  411. *
  412. * @param sheet The workbook sheet to look at.
  413. * @param rowIx The 0-based index of the row.
  414. * @param colIx The 0-based index of the cell.
  415. * @return cell at the given location, its base merged cell, or null if not defined
  416. * @throws NullPointerException if sheet is null
  417. */
  418. public static Cell getCellWithMerges(Sheet sheet, int rowIx, int colIx) {
  419. final Cell c = getCell(sheet, rowIx, colIx);
  420. if (c != null) return c;
  421. for (CellRangeAddress mergedRegion : sheet.getMergedRegions()) {
  422. if (mergedRegion.isInRange(rowIx, colIx)) {
  423. // The cell wanted is in this merged range
  424. // Return the primary (top-left) cell for the range
  425. Row r = sheet.getRow(mergedRegion.getFirstRow());
  426. if (r != null) {
  427. return r.getCell(mergedRegion.getFirstColumn());
  428. }
  429. }
  430. }
  431. // If we get here, then the cell isn't defined, and doesn't
  432. // live within any merged regions
  433. return null;
  434. }
  435. }