Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

HSSFRichTextString.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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.hssf.usermodel;
  16. import java.util.Iterator;
  17. import org.apache.poi.hssf.model.Workbook;
  18. import org.apache.poi.hssf.record.LabelSSTRecord;
  19. import org.apache.poi.hssf.record.UnicodeString;
  20. import org.apache.poi.ss.usermodel.Font;
  21. import org.apache.poi.ss.usermodel.RichTextString;
  22. /**
  23. * Rich text unicode string. These strings can have fonts applied to
  24. * arbitary parts of the string.
  25. *
  26. * <p>
  27. * Note, that in certain cases creating too many HSSFRichTextString cells may cause Excel 2003 and lower to crash
  28. * when changing the color of the cells and then saving the Excel file. Compare two snippets that produce equivalent output:
  29. *
  30. * <p><blockquote><pre>
  31. * HSSFCell hssfCell = row.createCell(idx);
  32. * //rich text consists of two runs
  33. * HSSFRichTextString richString = new HSSFRichTextString( "Hello, World!" );
  34. * richString.applyFont( 0, 6, font1 );
  35. * richString.applyFont( 6, 13, font2 );
  36. * hssfCell.setCellValue( richString );
  37. * </pre></blockquote>
  38. *
  39. * and
  40. *
  41. * <p><blockquote><pre>
  42. * //create a cell style and assign the first font to it
  43. * HSSFCellStyle style = workbook.createCellStyle();
  44. * style.setFont(font1);
  45. *
  46. * HSSFCell hssfCell = row.createCell(idx);
  47. * hssfCell.setCellStyle(style);
  48. *
  49. * //rich text consists of one run overriding the cell style
  50. * HSSFRichTextString richString = new HSSFRichTextString( "Hello, World!" );
  51. * richString.applyFont( 6, 13, font2 );
  52. * hssfCell.setCellValue( richString );
  53. * </pre></blockquote><p>
  54. *
  55. * Excel always uses the latter approach: for a reach text containing N runs Excel saves the font of the first run in the cell's
  56. * style and subsequent N-1 runs override this font.
  57. *
  58. * <p> For more information regarding this behavior please consult Bugzilla 47543:
  59. *
  60. * <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=47543">
  61. * https://issues.apache.org/bugzilla/show_bug.cgi?id=47543</a>
  62. * <p>
  63. *
  64. * @author Glen Stampoultzis (glens at apache.org)
  65. * @author Jason Height (jheight at apache.org)
  66. */
  67. public final class HSSFRichTextString implements Comparable<HSSFRichTextString>, RichTextString {
  68. /** Place holder for indicating that NO_FONT has been applied here */
  69. public static final short NO_FONT = 0;
  70. private UnicodeString _string;
  71. private Workbook _book;
  72. private LabelSSTRecord _record;
  73. public HSSFRichTextString()
  74. {
  75. this("");
  76. }
  77. public HSSFRichTextString(String string) {
  78. if (string == null) {
  79. _string = new UnicodeString("");
  80. } else {
  81. _string = new UnicodeString(string);
  82. }
  83. }
  84. HSSFRichTextString(Workbook book, LabelSSTRecord record) {
  85. setWorkbookReferences(book, record);
  86. _string = book.getSSTString(record.getSSTIndex());
  87. }
  88. /** This must be called to setup the internal work book references whenever
  89. * a RichTextString is added to a cell
  90. */
  91. void setWorkbookReferences(Workbook book, LabelSSTRecord record) {
  92. _book = book;
  93. _record = record;
  94. }
  95. /** Called whenever the unicode string is modified. When it is modified
  96. * we need to create a new SST index, so that other LabelSSTRecords will not
  97. * be affected by changes that we make to this string.
  98. */
  99. private UnicodeString cloneStringIfRequired() {
  100. if (_book == null)
  101. return _string;
  102. UnicodeString s = (UnicodeString)_string.clone();
  103. return s;
  104. }
  105. private void addToSSTIfRequired() {
  106. if (_book != null) {
  107. int index = _book.addSSTString(_string);
  108. _record.setSSTIndex(index);
  109. //The act of adding the string to the SST record may have meant that
  110. //an existing string was returned for the index, so update our local version
  111. _string = _book.getSSTString(index);
  112. }
  113. }
  114. /**
  115. * Applies a font to the specified characters of a string.
  116. *
  117. * @param startIndex The start index to apply the font to (inclusive)
  118. * @param endIndex The end index to apply the font to (exclusive)
  119. * @param fontIndex The font to use.
  120. */
  121. public void applyFont(int startIndex, int endIndex, short fontIndex)
  122. {
  123. if (startIndex > endIndex)
  124. throw new IllegalArgumentException("Start index must be less than end index.");
  125. if (startIndex < 0 || endIndex > length())
  126. throw new IllegalArgumentException("Start and end index not in range.");
  127. if (startIndex == endIndex)
  128. return;
  129. //Need to check what the font is currently, so we can reapply it after
  130. //the range is completed
  131. short currentFont = NO_FONT;
  132. if (endIndex != length()) {
  133. currentFont = this.getFontAtIndex(endIndex);
  134. }
  135. //Need to clear the current formatting between the startIndex and endIndex
  136. _string = cloneStringIfRequired();
  137. Iterator formatting = _string.formatIterator();
  138. if (formatting != null) {
  139. while (formatting.hasNext()) {
  140. UnicodeString.FormatRun r = (UnicodeString.FormatRun)formatting.next();
  141. if ((r.getCharacterPos() >= startIndex) && (r.getCharacterPos() < endIndex))
  142. formatting.remove();
  143. }
  144. }
  145. _string.addFormatRun(new UnicodeString.FormatRun((short)startIndex, fontIndex));
  146. if (endIndex != length())
  147. _string.addFormatRun(new UnicodeString.FormatRun((short)endIndex, currentFont));
  148. addToSSTIfRequired();
  149. }
  150. /**
  151. * Applies a font to the specified characters of a string.
  152. *
  153. * @param startIndex The start index to apply the font to (inclusive)
  154. * @param endIndex The end index to apply to font to (exclusive)
  155. * @param font The index of the font to use.
  156. */
  157. public void applyFont(int startIndex, int endIndex, Font font)
  158. {
  159. applyFont(startIndex, endIndex, ((HSSFFont) font).getIndex());
  160. }
  161. /**
  162. * Sets the font of the entire string.
  163. * @param font The font to use.
  164. */
  165. public void applyFont(Font font)
  166. {
  167. applyFont(0, _string.getCharCount(), font);
  168. }
  169. /**
  170. * Removes any formatting that may have been applied to the string.
  171. */
  172. public void clearFormatting() {
  173. _string = cloneStringIfRequired();
  174. _string.clearFormatting();
  175. addToSSTIfRequired();
  176. }
  177. /**
  178. * Returns the plain string representation.
  179. */
  180. public String getString()
  181. {
  182. return _string.getString();
  183. }
  184. /**
  185. * Used internally by the HSSFCell to get the internal
  186. * string value.
  187. * Will ensure the string is not shared
  188. */
  189. UnicodeString getUnicodeString() {
  190. return cloneStringIfRequired();
  191. }
  192. /**
  193. * Returns the raw, probably shared Unicode String.
  194. * Used when tweaking the styles, eg updating font
  195. * positions.
  196. * Changes to this string may well effect
  197. * other RichTextStrings too!
  198. */
  199. UnicodeString getRawUnicodeString() {
  200. return _string;
  201. }
  202. /** Used internally by the HSSFCell to set the internal string value*/
  203. void setUnicodeString(UnicodeString str) {
  204. this._string = str;
  205. }
  206. /**
  207. * @return the number of characters in the text.
  208. */
  209. public int length() {
  210. return _string.getCharCount();
  211. }
  212. /**
  213. * Returns the font in use at a particular index.
  214. *
  215. * @param index The index.
  216. * @return The font that's currently being applied at that
  217. * index or null if no font is being applied or the
  218. * index is out of range.
  219. */
  220. public short getFontAtIndex( int index )
  221. {
  222. int size = _string.getFormatRunCount();
  223. UnicodeString.FormatRun currentRun = null;
  224. for (int i=0;i<size;i++) {
  225. UnicodeString.FormatRun r = _string.getFormatRun(i);
  226. if (r.getCharacterPos() > index) {
  227. break;
  228. }
  229. currentRun = r;
  230. }
  231. if (currentRun == null) {
  232. return NO_FONT;
  233. }
  234. return currentRun.getFontIndex();
  235. }
  236. /**
  237. * @return The number of formatting runs used. There will always be at
  238. * least one of font NO_FONT.
  239. *
  240. * @see #NO_FONT
  241. */
  242. public int numFormattingRuns()
  243. {
  244. return _string.getFormatRunCount();
  245. }
  246. /**
  247. * The index within the string to which the specified formatting run applies.
  248. * @param index the index of the formatting run
  249. * @return the index within the string.
  250. */
  251. public int getIndexOfFormattingRun(int index)
  252. {
  253. UnicodeString.FormatRun r = _string.getFormatRun(index);
  254. return r.getCharacterPos();
  255. }
  256. /**
  257. * Gets the font used in a particular formatting run.
  258. *
  259. * @param index the index of the formatting run
  260. * @return the font number used.
  261. */
  262. public short getFontOfFormattingRun(int index)
  263. {
  264. UnicodeString.FormatRun r = _string.getFormatRun(index);
  265. return r.getFontIndex();
  266. }
  267. /**
  268. * Compares one rich text string to another.
  269. */
  270. public int compareTo(HSSFRichTextString r) {
  271. return _string.compareTo(r._string);
  272. }
  273. public boolean equals(Object o) {
  274. if (o instanceof HSSFRichTextString) {
  275. return _string.equals(((HSSFRichTextString)o)._string);
  276. }
  277. return false;
  278. }
  279. /**
  280. * @return the plain text representation of this string.
  281. */
  282. public String toString()
  283. {
  284. return _string.toString();
  285. }
  286. /**
  287. * Applies the specified font to the entire string.
  288. *
  289. * @param fontIndex the font to apply.
  290. */
  291. public void applyFont( short fontIndex )
  292. {
  293. applyFont(0, _string.getCharCount(), fontIndex);
  294. }
  295. }