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.

quick-guide.xml 88KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--
  3. ====================================================================
  4. Licensed to the Apache Software Foundation (ASF) under one or more
  5. contributor license agreements. See the NOTICE file distributed with
  6. this work for additional information regarding copyright ownership.
  7. The ASF licenses this file to You under the Apache License, Version 2.0
  8. (the "License"); you may not use this file except in compliance with
  9. the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. ====================================================================
  17. -->
  18. <!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V1.1//EN" "../dtd/document-v11.dtd">
  19. <document>
  20. <header>
  21. <title>Busy Developers' Guide to HSSF and XSSF Features</title>
  22. </header>
  23. <body>
  24. <section><title>Busy Developers' Guide to Features</title>
  25. <p>
  26. Want to use HSSF and XSSF read and write spreadsheets in a hurry? This
  27. guide is for you. If you're after more in-depth coverage of the HSSF and
  28. XSSF user-APIs, please consult the <link href="how-to.html">HOWTO</link>
  29. guide as it contains actual descriptions of how to use this stuff.
  30. </p>
  31. <section><title>Index of Features</title>
  32. <ul>
  33. <li><link href="#NewWorkbook">How to create a new workbook</link></li>
  34. <li><link href="#NewSheet">How to create a sheet</link></li>
  35. <li><link href="#CreateCells">How to create cells</link></li>
  36. <li><link href="#CreateDateCells">How to create date cells</link></li>
  37. <li><link href="#CellTypes">Working with different types of cells</link></li>
  38. <li><link href="#Iterator">Iterate over rows and cells</link></li>
  39. <li><link href="#CellContents">Getting the cell contents</link></li>
  40. <li><link href="#TextExtraction">Text Extraction</link></li>
  41. <li><link href="#Alignment">Aligning cells</link></li>
  42. <li><link href="#Borders">Working with borders</link></li>
  43. <li><link href="#FillsAndFrills">Fills and color</link></li>
  44. <li><link href="#MergedCells">Merging cells</link></li>
  45. <li><link href="#WorkingWithFonts">Working with fonts</link></li>
  46. <li><link href="#CustomColors">Custom colors</link></li>
  47. <li><link href="#ReadWriteWorkbook">Reading and writing</link></li>
  48. <li><link href="#NewLinesInCells">Use newlines in cells.</link></li>
  49. <li><link href="#DataFormats">Create user defined data formats</link></li>
  50. <li><link href="#FitTo">Fit Sheet to One Page</link></li>
  51. <li><link href="#PrintArea2">Set print area for a sheet</link></li>
  52. <li><link href="#FooterPageNumbers">Set page numbers on the footer of a sheet</link></li>
  53. <li><link href="#ShiftRows">Shift rows</link></li>
  54. <li><link href="#SelectSheet">Set a sheet as selected</link></li>
  55. <li><link href="#Zoom">Set the zoom magnification for a sheet</link></li>
  56. <li><link href="#Splits">Create split and freeze panes</link></li>
  57. <li><link href="#Repeating">Repeating rows and columns</link></li>
  58. <li><link href="#HeaderFooter">Headers and Footers</link></li>
  59. <li><link href="#DrawingShapes">Drawing Shapes</link></li>
  60. <li><link href="#StylingShapes">Styling Shapes</link></li>
  61. <li><link href="#Graphics2d">Shapes and Graphics2d</link></li>
  62. <li><link href="#Outlining">Outlining</link></li>
  63. <li><link href="#Images">Images</link></li>
  64. <li><link href="#NamedRanges">Named Ranges and Named Cells</link></li>
  65. <li><link href="#CellComments">How to set cell comments</link></li>
  66. <li><link href="#Autofit">How to adjust column width to fit the contents</link></li>
  67. <li><link href="#Hyperlinks">Hyperlinks</link></li>
  68. <li><link href="#Validation">Data Validations</link></li>
  69. <li><link href="#Embedded">Embedded Objects</link></li>
  70. <li><link href="#Autofilter">Autofilters</link></li>
  71. <li><link href="#ConditionalFormatting">Conditional Formatting</link></li>
  72. <li><link href="#Hiding">Hiding and Un-Hiding Rows</link></li>
  73. </ul>
  74. </section>
  75. <section><title>Features</title>
  76. <anchor id="NewWorkbook"/>
  77. <section><title>New Workbook</title>
  78. <source>
  79. Workbook wb = new HSSFWorkbook();
  80. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  81. wb.write(fileOut);
  82. fileOut.close();
  83. Workbook wb = new XSSFWorkbook();
  84. FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
  85. wb.write(fileOut);
  86. fileOut.close();
  87. </source>
  88. </section>
  89. <anchor id="NewSheet"/>
  90. <section><title>New Sheet</title>
  91. <source>
  92. Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
  93. Sheet sheet1 = wb.createSheet("new sheet");
  94. Sheet sheet2 = wb.createSheet("second sheet");
  95. // Note that sheet name is Excel must not exceed 31 characters
  96. // and must not contain any of the any of the following characters:
  97. // 0x0000
  98. // 0x0003
  99. // colon (:)
  100. // backslash (\)
  101. // asterisk (*)
  102. // question mark (?)
  103. // forward slash (/)
  104. // opening square bracket ([)
  105. // closing square bracket (])
  106. // You can use org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
  107. // for a safe way to create valid names, this utility replaces invalid characters with a space (' ')
  108. String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); // returns " O'Brien's sales "
  109. Sheet sheet3 = wb.createSheet(safeName);
  110. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  111. wb.write(fileOut);
  112. fileOut.close();
  113. </source>
  114. </section>
  115. <anchor id="CreateCells"/>
  116. <section><title>Creating Cells</title>
  117. <source>
  118. Workbook wb = new HSSFWorkbook();
  119. //Workbook wb = new XSSFWorkbook();
  120. CreationHelper createHelper = wb.getCreationHelper();
  121. Sheet sheet = wb.createSheet("new sheet");
  122. // Create a row and put some cells in it. Rows are 0 based.
  123. Row row = sheet.createRow((short)0);
  124. // Create a cell and put a value in it.
  125. Cell cell = row.createCell(0);
  126. cell.setCellValue(1);
  127. // Or do it on one line.
  128. row.createCell(1).setCellValue(1.2);
  129. row.createCell(2).setCellValue(
  130. createHelper.createRichTextString("This is a string"));
  131. row.createCell(3).setCellValue(true);
  132. // Write the output to a file
  133. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  134. wb.write(fileOut);
  135. fileOut.close();
  136. </source>
  137. </section>
  138. <anchor id="CreateDateCells"/>
  139. <section><title>Creating Date Cells</title>
  140. <source>
  141. Workbook wb = new HSSFWorkbook();
  142. //Workbook wb = new XSSFWorkbook();
  143. CreationHelper createHelper = wb.getCreationHelper();
  144. Sheet sheet = wb.createSheet("new sheet");
  145. // Create a row and put some cells in it. Rows are 0 based.
  146. Row row = sheet.createRow(0);
  147. // Create a cell and put a date value in it. The first cell is not styled
  148. // as a date.
  149. Cell cell = row.createCell(0);
  150. cell.setCellValue(new Date());
  151. // we style the second cell as a date (and time). It is important to
  152. // create a new cell style from the workbook otherwise you can end up
  153. // modifying the built in style and effecting not only this cell but other cells.
  154. CellStyle cellStyle = wb.createCellStyle();
  155. cellStyle.setDataFormat(
  156. createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
  157. cell = row.createCell(1);
  158. cell.setCellValue(new Date());
  159. cell.setCellStyle(cellStyle);
  160. //you can also set date as java.util.Calendar
  161. cell = row.createCell(2);
  162. cell.setCellValue(Calendar.getInstance());
  163. cell.setCellStyle(cellStyle);
  164. // Write the output to a file
  165. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  166. wb.write(fileOut);
  167. fileOut.close();
  168. </source>
  169. </section>
  170. <anchor id="CellTypes"/>
  171. <section><title>Working with different types of cells</title>
  172. <source>
  173. Workbook wb = new HSSFWorkbook();
  174. Sheet sheet = wb.createSheet("new sheet");
  175. Row row = sheet.createRow((short)2);
  176. row.createCell(0).setCellValue(1.1);
  177. row.createCell(1).setCellValue(new Date());
  178. row.createCell(2).setCellValue(Calendar.getInstance());
  179. row.createCell(3).setCellValue("a string");
  180. row.createCell(4).setCellValue(true);
  181. row.createCell(5).setCellType(Cell.CELL_TYPE_ERROR);
  182. // Write the output to a file
  183. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  184. wb.write(fileOut);
  185. fileOut.close();
  186. </source>
  187. </section>
  188. <anchor id="Alignment"/>
  189. <section><title>Demonstrates various alignment options</title>
  190. <source>
  191. public static void main(String[] args) throws Exception {
  192. Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
  193. Sheet sheet = wb.createSheet();
  194. Row row = sheet.createRow((short) 2);
  195. row.setHeightInPoints(30);
  196. createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
  197. createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
  198. createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
  199. createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
  200. createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
  201. createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
  202. createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);
  203. // Write the output to a file
  204. FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx");
  205. wb.write(fileOut);
  206. fileOut.close();
  207. }
  208. /**
  209. * Creates a cell and aligns it a certain way.
  210. *
  211. * @param wb the workbook
  212. * @param row the row to create the cell in
  213. * @param column the column number to create the cell in
  214. * @param halign the horizontal alignment for the cell.
  215. */
  216. private static void createCell(Workbook wb, Row row, short column, short halign, short valign) {
  217. Cell cell = row.createCell(column);
  218. cell.setCellValue("Align It");
  219. CellStyle cellStyle = wb.createCellStyle();
  220. cellStyle.setAlignment(halign);
  221. cellStyle.setVerticalAlignment(valign);
  222. cell.setCellStyle(cellStyle);
  223. }
  224. </source>
  225. </section>
  226. <anchor id="Borders"/>
  227. <section><title>Working with borders</title>
  228. <source>
  229. Workbook wb = new HSSFWorkbook();
  230. Sheet sheet = wb.createSheet("new sheet");
  231. // Create a row and put some cells in it. Rows are 0 based.
  232. Row row = sheet.createRow(1);
  233. // Create a cell and put a value in it.
  234. Cell cell = row.createCell(1);
  235. cell.setCellValue(4);
  236. // Style the cell with borders all around.
  237. CellStyle style = wb.createCellStyle();
  238. style.setBorderBottom(CellStyle.BORDER_THIN);
  239. style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  240. style.setBorderLeft(CellStyle.BORDER_THIN);
  241. style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
  242. style.setBorderRight(CellStyle.BORDER_THIN);
  243. style.setRightBorderColor(IndexedColors.BLUE.getIndex());
  244. style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
  245. style.setTopBorderColor(IndexedColors.BLACK.getIndex());
  246. cell.setCellStyle(style);
  247. // Write the output to a file
  248. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  249. wb.write(fileOut);
  250. fileOut.close();
  251. </source>
  252. </section>
  253. <anchor id="Iterator"/>
  254. <section><title>Iterate over rows and cells</title>
  255. <p>Sometimes, you'd like to just iterate over all the rows in
  256. a sheet, or all the cells in a row. This is possible with
  257. a simple for loop.</p>
  258. <p>Luckily, this is very easy. Row defines a
  259. <em>CellIterator</em> inner class to handle iterating over
  260. the cells (get one with a call to <em>row.cellIterator()</em>),
  261. and Sheet provides a <em>rowIterator()</em> method to
  262. give an iterator over all the rows.</p>
  263. <p>Alternately, Sheet and Row both implement java.lang.Iterable,
  264. so using Java 1.5 you can simply take advantage
  265. of the built in "foreach" support - see below.</p>
  266. <source>
  267. sheet sheet = wb.getsheetat(0);
  268. for (iterator&lt;row&gt; rit = sheet.rowiterator(); rit.hasnext(); ) {
  269. row row = rit.next();
  270. for (iterator&lt;cell&gt; cit = row.celliterator(); cit.hasnext(); ) {
  271. cell cell = cit.next();
  272. // do something here
  273. }
  274. }
  275. </source>
  276. </section>
  277. <section><title>Iterate over rows and cells using Java 1.5 foreach loops</title>
  278. <p>Sometimes, you'd like to just iterate over all the rows in
  279. a sheet, or all the cells in a row. If you are using Java
  280. 5 or later, then this is especially handy, as it'll allow the
  281. new foreach loop support to work.</p>
  282. <p>Luckily, this is very easy. Both Sheet and Row
  283. implement <em>java.lang.Iterable</em> to allow foreach
  284. loops. For Row this allows access to the
  285. <em>CellIterator</em> inner class to handle iterating over
  286. the cells, and for Sheet gives the
  287. <em>rowIterator()</em> to iterator over all the rows.</p>
  288. <source>
  289. Sheet sheet = wb.getSheetAt(0);
  290. for (Row row : sheet) {
  291. for (Cell cell : row) {
  292. // Do something here
  293. }
  294. }
  295. </source>
  296. </section>
  297. <anchor id="CellContents"/>
  298. <section><title>Getting the cell contents</title>
  299. <p>To get the contents of a cell, you first need to
  300. know what kind of cell it is (asking a string cell
  301. for its numeric contents will get you a
  302. NumberFormatException for example). So, you will
  303. want to switch on the cell's type, and then call
  304. the appropriate getter for that cell.</p>
  305. <p>In the code below, we loop over every cell
  306. in one sheet, print out the cell's reference
  307. (eg A3), and then the cell's contents.</p>
  308. <source>
  309. // import org.apache.poi.ss.usermodel.*;
  310. Sheet sheet1 = wb.getSheetAt(0);
  311. for (Row row : sheet1) {
  312. for (Cell cell : row) {
  313. CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
  314. System.out.print(cellRef.formatAsString());
  315. System.out.print(" - ");
  316. switch (cell.getCellType()) {
  317. case Cell.CELL_TYPE_STRING:
  318. System.out.println(cell.getRichStringCellValue().getString());
  319. break;
  320. case Cell.CELL_TYPE_NUMERIC:
  321. if (DateUtil.isCellDateFormatted(cell)) {
  322. System.out.println(cell.getDateCellValue());
  323. } else {
  324. System.out.println(cell.getNumericCellValue());
  325. }
  326. break;
  327. case Cell.CELL_TYPE_BOOLEAN:
  328. System.out.println(cell.getBooleanCellValue());
  329. break;
  330. case Cell.CELL_TYPE_FORMULA:
  331. System.out.println(cell.getCellFormula());
  332. break;
  333. default:
  334. System.out.println();
  335. }
  336. }
  337. }
  338. </source>
  339. </section>
  340. <anchor id="TextExtraction"/>
  341. <section><title>Text Extraction</title>
  342. <p>For most text extraction requirements, the standard
  343. ExcelExtractor class should provide all you need.</p>
  344. <source>
  345. InputStream inp = new FileInputStream("workbook.xls");
  346. HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
  347. ExcelExtractor extractor = new ExcelExtractor(wb);
  348. extractor.setFormulasNotResults(true);
  349. extractor.setIncludeSheetNames(false);
  350. String text = extractor.getText();
  351. </source>
  352. <p>For very fancy text extraction, XLS to CSV etc,
  353. take a look at
  354. <em>/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java</em>
  355. </p>
  356. </section>
  357. <anchor id="FillsAndFrills"/>
  358. <section><title>Fills and colors</title>
  359. <source>
  360. Workbook wb = new XSSFWorkbook();
  361. Sheet sheet = wb.createSheet("new sheet");
  362. // Create a row and put some cells in it. Rows are 0 based.
  363. Row row = sheet.createRow((short) 1);
  364. // Aqua background
  365. CellStyle style = wb.createCellStyle();
  366. style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
  367. style.setFillPattern(CellStyle.BIG_SPOTS);
  368. Cell cell = row.createCell((short) 1);
  369. cell.setCellValue("X");
  370. cell.setCellStyle(style);
  371. // Orange "foreground", foreground being the fill foreground not the font color.
  372. style = wb.createCellStyle();
  373. style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
  374. style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  375. cell = row.createCell((short) 2);
  376. cell.setCellValue("X");
  377. cell.setCellStyle(style);
  378. // Write the output to a file
  379. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  380. wb.write(fileOut);
  381. fileOut.close();
  382. </source>
  383. </section>
  384. <anchor id="MergedCells"/>
  385. <section><title>Merging cells</title>
  386. <source>
  387. Workbook wb = new HSSFWorkbook();
  388. Sheet sheet = wb.createSheet("new sheet");
  389. Row row = sheet.createRow((short) 1);
  390. Cell cell = row.createCell((short) 1);
  391. cell.setCellValue("This is a test of merging");
  392. sheet.addMergedRegion(new CellRangeAddress(
  393. 1, //first row (0-based)
  394. 1, //last row (0-based)
  395. 1, //first column (0-based)
  396. 2 //last column (0-based)
  397. ));
  398. // Write the output to a file
  399. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  400. wb.write(fileOut);
  401. fileOut.close();
  402. </source>
  403. </section>
  404. <anchor id="WorkingWithFonts"/>
  405. <section><title>Working with fonts</title>
  406. <source>
  407. Workbook wb = new HSSFWorkbook();
  408. Sheet sheet = wb.createSheet("new sheet");
  409. // Create a row and put some cells in it. Rows are 0 based.
  410. Row row = sheet.createRow(1);
  411. // Create a new font and alter it.
  412. Font font = wb.createFont();
  413. font.setFontHeightInPoints((short)24);
  414. font.setFontName("Courier New");
  415. font.setItalic(true);
  416. font.setStrikeout(true);
  417. // Fonts are set into a style so create a new one to use.
  418. CellStyle style = wb.createCellStyle();
  419. style.setFont(font);
  420. // Create a cell and put a value in it.
  421. Cell cell = row.createCell(1);
  422. cell.setCellValue("This is a test of fonts");
  423. cell.setCellStyle(style);
  424. // Write the output to a file
  425. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  426. wb.write(fileOut);
  427. fileOut.close();
  428. </source>
  429. <p>
  430. Note, the maximum number of unique fonts in a workbook is limited to 32767 (
  431. the maximum positive short). You should re-use fonts in your apllications instead of
  432. creating a font for each cell.
  433. Examples:
  434. </p>
  435. <p><strong>Wrong:</strong></p>
  436. <source>
  437. for (int i = 0; i &lt; 10000; i++) {
  438. Row row = sheet.createRow(i);
  439. Cell cell = row.createCell((short) 0);
  440. CellStyle style = workbook.createCellStyle();
  441. Font font = workbook.createFont();
  442. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  443. style.setFont(font);
  444. cell.setCellStyle(style);
  445. }
  446. </source>
  447. <p><strong>Correct:</strong></p>
  448. <source>
  449. CellStyle style = workbook.createCellStyle();
  450. Font font = workbook.createFont();
  451. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  452. style.setFont(font);
  453. for (int i = 0; i &lt; 10000; i++) {
  454. Row row = sheet.createRow(i);
  455. Cell cell = row.createCell((short) 0);
  456. cell.setCellStyle(style);
  457. }
  458. </source>
  459. </section>
  460. <anchor id="CustomColors"/>
  461. <section><title>Custom colors</title>
  462. <p><strong>HSSF:</strong></p>
  463. <source>
  464. HSSFWorkbook wb = new HSSFWorkbook();
  465. HSSFSheet sheet = wb.createSheet();
  466. HSSFRow row = sheet.createRow((short) 0);
  467. HSSFCell cell = row.createCell((short) 0);
  468. cell.setCellValue("Default Palette");
  469. //apply some colors from the standard palette,
  470. // as in the previous examples.
  471. //we'll use red text on a lime background
  472. HSSFCellStyle style = wb.createCellStyle();
  473. style.setFillForegroundColor(HSSFColor.LIME.index);
  474. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  475. HSSFFont font = wb.createFont();
  476. font.setColor(HSSFColor.RED.index);
  477. style.setFont(font);
  478. cell.setCellStyle(style);
  479. //save with the default palette
  480. FileOutputStream out = new FileOutputStream("default_palette.xls");
  481. wb.write(out);
  482. out.close();
  483. //now, let's replace RED and LIME in the palette
  484. // with a more attractive combination
  485. // (lovingly borrowed from freebsd.org)
  486. cell.setCellValue("Modified Palette");
  487. //creating a custom palette for the workbook
  488. HSSFPalette palette = wb.getCustomPalette();
  489. //replacing the standard red with freebsd.org red
  490. palette.setColorAtIndex(HSSFColor.RED.index,
  491. (byte) 153, //RGB red (0-255)
  492. (byte) 0, //RGB green
  493. (byte) 0 //RGB blue
  494. );
  495. //replacing lime with freebsd.org gold
  496. palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
  497. //save with the modified palette
  498. // note that wherever we have previously used RED or LIME, the
  499. // new colors magically appear
  500. out = new FileOutputStream("modified_palette.xls");
  501. wb.write(out);
  502. out.close();
  503. </source>
  504. <p><strong>XSSF:</strong></p>
  505. <source>
  506. XSSFWorkbook wb = new XSSFWorkbook();
  507. XSSFSheet sheet = wb.createSheet();
  508. XSSFRow row = sheet.createRow(0);
  509. XSSFCell cell = row.createCell( 0);
  510. cell.setCellValue("custom XSSF colors");
  511. XSSFCellStyle style1 = wb.createCellStyle();
  512. style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
  513. style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
  514. </source>
  515. </section>
  516. <anchor id="ReadWriteWorkbook"/>
  517. <section><title>Reading and Rewriting Workbooks</title>
  518. <source>
  519. InputStream inp = new FileInputStream("workbook.xls");
  520. //InputStream inp = new FileInputStream("workbook.xlsx");
  521. Workbook wb = WorkbookFactory.create(inp);
  522. Sheet sheet = wb.getSheetAt(0);
  523. Row row = sheet.getRow(2);
  524. Cell cell = row.getCell(3);
  525. if (cell == null)
  526. cell = row.createCell(3);
  527. cell.setCellType(Cell.CELL_TYPE_STRING);
  528. cell.setCellValue("a test");
  529. // Write the output to a file
  530. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  531. wb.write(fileOut);
  532. fileOut.close();
  533. </source>
  534. </section>
  535. <anchor id="NewLinesInCells"/>
  536. <section><title>Using newlines in cells</title>
  537. <source>
  538. Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
  539. Sheet sheet = wb.createSheet();
  540. Row row = sheet.createRow(2);
  541. Cell cell = row.createCell(2);
  542. cell.setCellValue("Use \n with word wrap on to create a new line");
  543. //to enable newlines you need set a cell styles with wrap=true
  544. CellStyle cs = wb.createCellStyle();
  545. cs.setWrapText(true);
  546. cell.setCellStyle(cs);
  547. //increase row height to accomodate two lines of text
  548. row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
  549. //adjust column width to fit the content
  550. sheet.autoSizeColumn((short)2);
  551. FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
  552. wb.write(fileOut);
  553. fileOut.close();
  554. </source>
  555. </section>
  556. <anchor id="DataFormats"/>
  557. <section><title>Data Formats</title>
  558. <source>
  559. Workbook wb = new HSSFWorkbook();
  560. Sheet sheet = wb.createSheet("format sheet");
  561. CellStyle style;
  562. DataFormat format = wb.createDataFormat();
  563. Row row;
  564. Cell cell;
  565. short rowNum = 0;
  566. short colNum = 0;
  567. row = sheet.createRow(rowNum++);
  568. cell = row.createCell(colNum);
  569. cell.setCellValue(11111.25);
  570. style = wb.createCellStyle();
  571. style.setDataFormat(format.getFormat("0.0"));
  572. cell.setCellStyle(style);
  573. row = sheet.createRow(rowNum++);
  574. cell = row.createCell(colNum);
  575. cell.setCellValue(11111.25);
  576. style = wb.createCellStyle();
  577. style.setDataFormat(format.getFormat("#,##0.0000"));
  578. cell.setCellStyle(style);
  579. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  580. wb.write(fileOut);
  581. fileOut.close();
  582. </source>
  583. </section>
  584. <anchor id="FitTo"/>
  585. <section><title>Fit Sheet to One Page</title>
  586. <source>
  587. Workbook wb = new HSSFWorkbook();
  588. Sheet sheet = wb.createSheet("format sheet");
  589. PrintSetup ps = sheet.getPrintSetup();
  590. sheet.setAutobreaks(true);
  591. ps.setFitHeight((short)1);
  592. ps.setFitWidth((short)1);
  593. // Create various cells and rows for spreadsheet.
  594. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  595. wb.write(fileOut);
  596. fileOut.close();
  597. </source>
  598. </section>
  599. <anchor id="PrintArea2"/>
  600. <section><title>Set Print Area</title>
  601. <source>
  602. Workbook wb = new HSSFWorkbook();
  603. Sheet sheet = wb.createSheet("Sheet1");
  604. //sets the print area for the first sheet
  605. wb.setPrintArea(0, "$A$1:$C$2");
  606. //Alternatively:
  607. wb.setPrintArea(
  608. 0, //sheet index
  609. 0, //start column
  610. 1, //end column
  611. 0, //start row
  612. 0 //end row
  613. );
  614. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  615. wb.write(fileOut);
  616. fileOut.close();
  617. </source>
  618. </section>
  619. <anchor id="FooterPageNumbers"/>
  620. <section><title>Set Page Numbers on Footer</title>
  621. <source>
  622. Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
  623. Sheet sheet = wb.createSheet("format sheet");
  624. Footer footer = sheet.getFooter();
  625. footer.setRight( "Page " + HeaderFooter.page() + " of " + HeaderFooter.numPages() );
  626. // Create various cells and rows for spreadsheet.
  627. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  628. wb.write(fileOut);
  629. fileOut.close();
  630. </source>
  631. </section>
  632. <anchor id="ConvenienceFunctions"/>
  633. <section><title>Using the Convenience Functions</title>
  634. <p>
  635. The convenience functions provide
  636. utility features such as setting borders around merged
  637. regions and changing style attributes without explicitly
  638. creating new styles.
  639. </p>
  640. <source>
  641. Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook()
  642. Sheet sheet1 = wb.createSheet( "new sheet" );
  643. // Create a merged region
  644. Row row = sheet1.createRow( 1 );
  645. Row row2 = sheet1.createRow( 2 );
  646. Cell cell = row.createCell( 1 );
  647. cell.setCellValue( "This is a test of merging" );
  648. CellRangeAddress region = CellRangeAddress.valueOf("B2:E5");
  649. sheet1.addMergedRegion( region );
  650. // Set the border and border colors.
  651. final short borderMediumDashed = CellStyle.BORDER_MEDIUM_DASHED;
  652. RegionUtil.setBorderBottom( borderMediumDashed,
  653. region, sheet1, wb );
  654. RegionUtil.setBorderTop( borderMediumDashed,
  655. region, sheet1, wb );
  656. RegionUtil.setBorderLeft( borderMediumDashed,
  657. region, sheet1, wb );
  658. RegionUtil.setBorderRight( borderMediumDashed,
  659. region, sheet1, wb );
  660. RegionUtil.setBottomBorderColor(IndexedColors.AQUA.getIndex(), region, sheet1, wb);
  661. RegionUtil.setTopBorderColor(IndexedColors.AQUA.getIndex(), region, sheet1, wb);
  662. RegionUtil.setLeftBorderColor(IndexedColors.AQUA.getIndex(), region, sheet1, wb);
  663. RegionUtil.setRightBorderColor(IndexedColors.AQUA.getIndex(), region, sheet1, wb);
  664. // Shows some usages of HSSFCellUtil
  665. CellStyle style = wb.createCellStyle();
  666. style.setIndention((short)4);
  667. CellUtil.createCell(row, 8, "This is the value of the cell", style);
  668. Cell cell2 = CellUtil.createCell( row2, 8, "This is the value of the cell");
  669. CellUtil.setAlignment(cell2, wb, CellStyle.ALIGN_CENTER);
  670. // Write out the workbook
  671. FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );
  672. wb.write( fileOut );
  673. fileOut.close();
  674. </source>
  675. </section>
  676. <anchor id="ShiftRows"/>
  677. <section><title>Shift rows up or down on a sheet</title>
  678. <source>
  679. Workbook wb = new HSSFWorkbook();
  680. Sheet sheet = wb.createSheet("row sheet");
  681. // Create various cells and rows for spreadsheet.
  682. // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
  683. sheet.shiftRows(5, 10, -5);
  684. </source>
  685. </section>
  686. <anchor id="SelectSheet"/>
  687. <section><title>Set a sheet as selected</title>
  688. <source>
  689. Workbook wb = new HSSFWorkbook();
  690. Sheet sheet = wb.createSheet("row sheet");
  691. sheet.setSelected(true);
  692. </source>
  693. </section>
  694. <anchor id="Zoom"/>
  695. <section><title>Set the zoom magnification</title>
  696. <p>
  697. The zoom is expressed as a fraction. For example to
  698. express a zoom of 75% use 3 for the numerator and
  699. 4 for the denominator.
  700. </p>
  701. <source>
  702. Workbook wb = new HSSFWorkbook();
  703. Sheet sheet1 = wb.createSheet("new sheet");
  704. sheet1.setZoom(3,4); // 75 percent magnification
  705. </source>
  706. </section>
  707. <anchor id="Splits"/>
  708. <section><title>Splits and freeze panes</title>
  709. <p>
  710. There are two types of panes you can create; freeze panes and split panes.
  711. </p>
  712. <p>
  713. A freeze pane is split by columns and rows. You create
  714. a freeze pane using the following mechanism:
  715. </p>
  716. <p>
  717. sheet1.createFreezePane( 3, 2, 3, 2 );
  718. </p>
  719. <p>
  720. The first two parameters are the columns and rows you
  721. wish to split by. The second two parameters indicate
  722. the cells that are visible in the bottom right quadrant.
  723. </p>
  724. <p>
  725. Split pains appear differently. The split area is
  726. divided into four separate work area's. The split
  727. occurs at the pixel level and the user is able to
  728. adjust the split by dragging it to a new position.
  729. </p>
  730. <p>
  731. Split panes are created with the following call:
  732. </p>
  733. <p>
  734. sheet2.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
  735. </p>
  736. <p>
  737. The first parameter is the x position of the split.
  738. This is in 1/20th of a point. A point in this case
  739. seems to equate to a pixel. The second parameter is
  740. the y position of the split. Again in 1/20th of a point.
  741. </p>
  742. <p>
  743. The last parameter indicates which pane currently has
  744. the focus. This will be one of Sheet.PANE_LOWER_LEFT,
  745. PANE_LOWER_RIGHT, PANE_UPPER_RIGHT or PANE_UPPER_LEFT.
  746. </p>
  747. <source>
  748. Workbook wb = new HSSFWorkbook();
  749. Sheet sheet1 = wb.createSheet("new sheet");
  750. Sheet sheet2 = wb.createSheet("second sheet");
  751. Sheet sheet3 = wb.createSheet("third sheet");
  752. Sheet sheet4 = wb.createSheet("fourth sheet");
  753. // Freeze just one row
  754. sheet1.createFreezePane( 0, 1, 0, 1 );
  755. // Freeze just one column
  756. sheet2.createFreezePane( 1, 0, 1, 0 );
  757. // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
  758. sheet3.createFreezePane( 2, 2 );
  759. // Create a split with the lower left side being the active quadrant
  760. sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
  761. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  762. wb.write(fileOut);
  763. fileOut.close();
  764. </source>
  765. </section>
  766. <anchor id="Repeating"/>
  767. <section><title>Repeating rows and columns</title>
  768. <p>
  769. It's possible to set up repeating rows and columns in
  770. your printouts by using the setRepeatingRows() and
  771. setRepeatingColumns() methods in the Sheet class.
  772. </p>
  773. <p>
  774. These methods expect a CellRangeAddress parameter
  775. which specifies the range for the rows or columns to
  776. repeat.
  777. For setRepeatingRows(), it should specify a range of
  778. rows to repeat, with the column part spanning all
  779. columns.
  780. For setRepeatingColums(), it should specify a range of
  781. columns to repeat, with the row part spanning all
  782. rows.
  783. If the parameter is null, the repeating rows or columns
  784. will be removed.
  785. </p>
  786. <source>
  787. Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
  788. Sheet sheet1 = wb.createSheet("Sheet1");
  789. Sheet sheet2 = wb.createSheet("Sheet2");
  790. // Set the rows to repeat from row 4 to 5 on the first sheet.
  791. sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5"));
  792. // Set the columns to repeat from column A to C on the second sheet
  793. sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
  794. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  795. wb.write(fileOut);
  796. fileOut.close();
  797. </source>
  798. </section>
  799. <anchor id="HeaderFooter"/>
  800. <section><title>Headers and Footers</title>
  801. <p>
  802. Example is for headers but applies directly to footers.
  803. </p>
  804. <source>
  805. Workbook wb = new HSSFWorkbook();
  806. Sheet sheet = wb.createSheet("new sheet");
  807. Header header = sheet.getHeader();
  808. header.setCenter("Center Header");
  809. header.setLeft("Left Header");
  810. header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") +
  811. HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16");
  812. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
  813. wb.write(fileOut);
  814. fileOut.close();
  815. </source>
  816. </section>
  817. <anchor id="DrawingShapes"/>
  818. <section><title>Drawing Shapes</title>
  819. <p>
  820. POI supports drawing shapes using the Microsoft Office
  821. drawing tools. Shapes on a sheet are organized in a
  822. hiearchy of groups and and shapes. The top-most shape
  823. is the patriarch. This is not visisble on the sheet
  824. at all. To start drawing you need to call <code>createPatriarch</code>
  825. on the <code>HSSFSheet</code> class. This has the
  826. effect erasing any other shape information stored
  827. in that sheet. By default POI will leave shape
  828. records alone in the sheet unless you make a call to
  829. this method.
  830. </p>
  831. <p>
  832. To create a shape you have to go through the following
  833. steps:
  834. </p>
  835. <ol>
  836. <li>Create the patriarch.</li>
  837. <li>Create an anchor to position the shape on the sheet.</li>
  838. <li>Ask the patriarch to create the shape.</li>
  839. <li>Set the shape type (line, oval, rectangle etc...)</li>
  840. <li>Set any other style details converning the shape. (eg:
  841. line thickness, etc...)</li>
  842. </ol>
  843. <source>
  844. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
  845. a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
  846. HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1);
  847. shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
  848. </source>
  849. <p>
  850. Text boxes are created using a different call:
  851. </p>
  852. <source>
  853. HSSFTextbox textbox1 = patriarch.createTextbox(
  854. new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)2,2));
  855. textbox1.setString(new HSSFRichTextString("This is a test") );
  856. </source>
  857. <p>
  858. It's possible to use different fonts to style parts of
  859. the text in the textbox. Here's how:
  860. </p>
  861. <source>
  862. HSSFFont font = wb.createFont();
  863. font.setItalic(true);
  864. font.setUnderline(HSSFFont.U_DOUBLE);
  865. HSSFRichTextString string = new HSSFRichTextString("Woo!!!");
  866. string.applyFont(2,5,font);
  867. textbox.setString(string );
  868. </source>
  869. <p>
  870. Just as can be done manually using Excel, it is possible
  871. to group shapes together. This is done by calling
  872. <code>createGroup()</code> and then creating the shapes
  873. using those groups.
  874. </p>
  875. <p>
  876. It's also possible to create groups within groups.
  877. </p>
  878. <warning>Any group you create should contain at least two
  879. other shapes or subgroups.</warning>
  880. <p>
  881. Here's how to create a shape group:
  882. </p>
  883. <source>
  884. // Create a shape group.
  885. HSSFShapeGroup group = patriarch.createGroup(
  886. new HSSFClientAnchor(0,0,900,200,(short)2,2,(short)2,2));
  887. // Create a couple of lines in the group.
  888. HSSFSimpleShape shape1 = group.createShape(new HSSFChildAnchor(3,3,500,500));
  889. shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
  890. ( (HSSFChildAnchor) shape1.getAnchor() ).setAnchor((short)3,3,500,500);
  891. HSSFSimpleShape shape2 = group.createShape(new HSSFChildAnchor((short)1,200,400,600));
  892. shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
  893. </source>
  894. <p>
  895. If you're being observant you'll noticed that the shapes
  896. that are added to the group use a new type of anchor:
  897. the <code>HSSFChildAnchor</code>. What happens is that
  898. the created group has it's own coordinate space for
  899. shapes that are placed into it. POI defaults this to
  900. (0,0,1023,255) but you are able to change it as desired.
  901. Here's how:
  902. </p>
  903. <source>
  904. myGroup.setCoordinates(10,10,20,20); // top-left, bottom-right
  905. </source>
  906. <p>
  907. If you create a group within a group it's also going
  908. to have it's own coordinate space.
  909. </p>
  910. </section>
  911. <anchor id="StylingShapes"/>
  912. <section><title>Styling Shapes</title>
  913. <p>
  914. By default shapes can look a little plain. It's possible
  915. to apply different styles to the shapes however. The
  916. sorts of things that can currently be done are:
  917. </p>
  918. <ul>
  919. <li>Change the fill color.</li>
  920. <li>Make a shape with no fill color.</li>
  921. <li>Change the thickness of the lines.</li>
  922. <li>Change the style of the lines. Eg: dashed, dotted.</li>
  923. <li>Change the line color.</li>
  924. </ul>
  925. <p>
  926. Here's an examples of how this is done:
  927. </p>
  928. <source>
  929. HSSFSimpleShape s = patriarch.createSimpleShape(a);
  930. s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
  931. s.setLineStyleColor(10,10,10);
  932. s.setFillColor(90,10,200);
  933. s.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3);
  934. s.setLineStyle(HSSFShape.LINESTYLE_DOTSYS);
  935. </source>
  936. </section>
  937. <anchor id="Graphics2d"/>
  938. <section><title>Shapes and Graphics2d</title>
  939. <p>
  940. While the native POI shape drawing commands are the
  941. recommended way to draw shapes in a shape it's sometimes
  942. desirable to use a standard API for compatibility with
  943. external libraries. With this in mind we created some
  944. wrappers for <code>Graphics</code> and <code>Graphics2d</code>.
  945. </p>
  946. <warning>
  947. It's important to not however before continuing that
  948. <code>Graphics2d</code> is a poor match to the capabilities
  949. of the Microsoft Office drawing commands. The older
  950. <code>Graphics</code> class offers a closer match but is
  951. still a square peg in a round hole.
  952. </warning>
  953. <p>
  954. All Graphics commands are issued into an <code>HSSFShapeGroup</code>.
  955. Here's how it's done:
  956. </p>
  957. <source>
  958. a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
  959. group = patriarch.createGroup( a );
  960. group.setCoordinates( 0, 0, 80 * 4 , 12 * 23 );
  961. float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / (float)Math.abs(group.getY2() - group.getY1());
  962. g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
  963. g2d = new EscherGraphics2d( g );
  964. drawChemicalStructure( g2d );
  965. </source>
  966. <p>
  967. The first thing we do is create the group and set it's coordinates
  968. to match what we plan to draw. Next we calculate a reasonable
  969. fontSizeMultipler then create the EscherGraphics object.
  970. Since what we really want is a <code>Graphics2d</code>
  971. object we create an EscherGraphics2d object and pass in
  972. the graphics object we created. Finally we call a routine
  973. that draws into the EscherGraphics2d object.
  974. </p>
  975. <p>
  976. The vertical points per pixel deserves some more explanation.
  977. One of the difficulties in converting Graphics calls
  978. into escher drawing calls is that Excel does not have
  979. the concept of absolute pixel positions. It measures
  980. it's cell widths in 'characters' and the cell heights in points.
  981. Unfortunately it's not defined exactly what type of character it's
  982. measuring. Presumably this is due to the fact that the Excel will be
  983. using different fonts on different platforms or even within the same
  984. platform.
  985. </p>
  986. <p>
  987. Because of this constraint we've had to implement the concept of a
  988. verticalPointsPerPixel. This the amount the font should be scaled by when
  989. you issue commands such as drawString(). To calculate this value
  990. use the follow formula:
  991. </p>
  992. <source>
  993. multipler = groupHeightInPoints / heightOfGroup
  994. </source>
  995. <p>
  996. The height of the group is calculated fairly simply by calculating the
  997. difference between the y coordinates of the bounding box of the shape. The
  998. height of the group can be calculated by using a convenience called
  999. <code>HSSFClientAnchor.getAnchorHeightInPoints()</code>.
  1000. </p>
  1001. <p>
  1002. Many of the functions supported by the graphics classes
  1003. are not complete. Here's some of the functions that are known
  1004. to work.
  1005. </p>
  1006. <ul>
  1007. <li>fillRect()</li>
  1008. <li>fillOval()</li>
  1009. <li>drawString()</li>
  1010. <li>drawOval()</li>
  1011. <li>drawLine()</li>
  1012. <li>clearRect()</li>
  1013. </ul>
  1014. <p>
  1015. Functions that are not supported will return and log a message
  1016. using the POI logging infrastructure (disabled by default).
  1017. </p>
  1018. </section>
  1019. <anchor id="Outlining"/>
  1020. <section>
  1021. <title>Outlining</title>
  1022. <p>
  1023. Outlines are great for grouping sections of information
  1024. together and can be added easily to columns and rows
  1025. using the POI API. Here's how:
  1026. </p>
  1027. <source>
  1028. Workbook wb = new HSSFWorkbook();
  1029. Sheet sheet1 = wb.createSheet("new sheet");
  1030. sheet1.groupRow( 5, 14 );
  1031. sheet1.groupRow( 7, 14 );
  1032. sheet1.groupRow( 16, 19 );
  1033. sheet1.groupColumn( (short)4, (short)7 );
  1034. sheet1.groupColumn( (short)9, (short)12 );
  1035. sheet1.groupColumn( (short)10, (short)11 );
  1036. FileOutputStream fileOut = new FileOutputStream(filename);
  1037. wb.write(fileOut);
  1038. fileOut.close();
  1039. </source>
  1040. <p>
  1041. To collapse (or expand) an outline use the following calls:
  1042. </p>
  1043. <source>
  1044. sheet1.setRowGroupCollapsed( 7, true );
  1045. sheet1.setColumnGroupCollapsed( (short)4, true );
  1046. </source>
  1047. <p>
  1048. The row/column you choose should contain an already
  1049. created group. It can be anywhere within the group.
  1050. </p>
  1051. </section>
  1052. </section>
  1053. </section>
  1054. <anchor id="Images"/>
  1055. <section>
  1056. <title>Images</title>
  1057. <p>
  1058. Images are part of the drawing support. To add an image just
  1059. call <code>createPicture()</code> on the drawing patriarch.
  1060. At the time of writing the following types are supported:
  1061. </p>
  1062. <ul>
  1063. <li>PNG</li>
  1064. <li>JPG</li>
  1065. <li>DIB</li>
  1066. </ul>
  1067. <p>
  1068. It should be noted that any existing drawings may be erased
  1069. once you add a image to a sheet.
  1070. </p>
  1071. <source>
  1072. //create a new workbook
  1073. Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
  1074. //add picture data to this workbook.
  1075. InputStream is = new FileInputStream("image1.jpeg");
  1076. byte[] bytes = IOUtils.toByteArray(is);
  1077. int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
  1078. is.close();
  1079. CreationHelper helper = wb.getCreationHelper();
  1080. //create sheet
  1081. Sheet sheet = wb.createSheet();
  1082. // Create the drawing patriarch. This is the top level container for all shapes.
  1083. Drawing drawing = sheet.createDrawingPatriarch();
  1084. //add a picture shape
  1085. ClientAnchor anchor = helper.createClientAnchor();
  1086. //set top-left corner of the picture,
  1087. //subsequent call of Picture#resize() will operate relative to it
  1088. anchor.setCol1(3);
  1089. anchor.setRow1(2);
  1090. Picture pict = drawing.createPicture(anchor, pictureIdx);
  1091. //auto-size picture relative to its top-left corner
  1092. pict.resize();
  1093. //save workbook
  1094. String file = "picture.xls";
  1095. if(wb instanceof XSSFWorkbook) file += "x";
  1096. FileOutputStream fileOut = new FileOutputStream(file);
  1097. wb.write(fileOut);
  1098. fileOut.close();
  1099. </source>
  1100. <warning>
  1101. Picture.resize() works only for JPEG and PNG. Other formats are not yet supported.
  1102. </warning>
  1103. <p>Reading images from a workbook:</p>
  1104. <source>
  1105. List lst = workbook.getAllPictures();
  1106. for (Iterator it = lst.iterator(); it.hasNext(); ) {
  1107. PictureData pict = (PictureData)it.next();
  1108. String ext = pict.suggestFileExtension();
  1109. byte[] data = pict.getData();
  1110. if (ext.equals("jpeg")){
  1111. FileOutputStream out = new FileOutputStream("pict.jpg");
  1112. out.write(data);
  1113. out.close();
  1114. }
  1115. }
  1116. </source>
  1117. </section>
  1118. <anchor id="NamedRanges"/>
  1119. <section>
  1120. <title>Named Ranges and Named Cells</title>
  1121. <p>
  1122. Named Range is a way to refer to a group of cells by a name. Named Cell is a
  1123. degenerate case of Named Range in that the 'group of cells' contains exactly one
  1124. cell. You can create as well as refer to cells in a workbook by their named range.
  1125. When working with Named Ranges, the classes: org.apache.poi.hssf.util.CellReference and
  1126. &amp; org.apache.poi.hssf.util.AreaReference are used (these
  1127. work for both XSSF and HSSF, despite the package name).
  1128. </p>
  1129. <p>
  1130. Creating Named Range / Named Cell
  1131. </p>
  1132. <source>
  1133. // setup code
  1134. String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
  1135. Workbook wb = new HSSFWorkbook();
  1136. Sheet sheet = wb.createSheet(sname);
  1137. sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);
  1138. // 1. create named range for a single cell using areareference
  1139. Name namedCell = wb.createName();
  1140. namedCell.setNameName(cname);
  1141. String reference = sname+"!A1:A1"; // area reference
  1142. namedCell.setRefersToFormula(reference);
  1143. // 2. create named range for a single cell using cellreference
  1144. Name namedCel2 = wb.createName();
  1145. namedCel2.setNameName(cname);
  1146. String reference = sname+"!A1"; // cell reference
  1147. namedCel2.setRefersToFormula(reference);
  1148. // 3. create named range for an area using AreaReference
  1149. Name namedCel3 = wb.createName();
  1150. namedCel3.setNameName(cname);
  1151. String reference = sname+"!A1:C5"; // area reference
  1152. namedCel3.setRefersToFormula(reference);
  1153. // 4. create named formula
  1154. Name namedCel4 = wb.createName();
  1155. namedCel4.setNameName("my_sum");
  1156. namedCel4.setRefersToFormula("SUM(sname+!$I$2:$I$6)");
  1157. </source>
  1158. <p>
  1159. Reading from Named Range / Named Cell
  1160. </p>
  1161. <source>
  1162. // setup code
  1163. String cname = "TestName";
  1164. Workbook wb = getMyWorkbook(); // retrieve workbook
  1165. // retrieve the named range
  1166. int namedCellIdx = wb.getNameIndex(cellName);
  1167. Name aNamedCell = wb.getNameAt(namedCellIdx);
  1168. // retrieve the cell at the named range and test its contents
  1169. AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
  1170. CellReference[] crefs = aref.getAllReferencedCells();
  1171. for (int i=0; i&lt;crefs.length; i++) {
  1172. Sheet s = wb.getSheet(crefs[i].getSheetName());
  1173. Row r = sheet.getRow(crefs[i].getRow());
  1174. Cell c = r.getCell(crefs[i].getCol());
  1175. // extract the cell contents based on cell type etc.
  1176. }
  1177. </source>
  1178. <p>
  1179. Reading from non-contiguous Named Ranges
  1180. </p>
  1181. <source>
  1182. // Setup code
  1183. String cname = "TestName";
  1184. Workbook wb = getMyWorkbook(); // retrieve workbook
  1185. // Retrieve the named range
  1186. // Will be something like "$C$10,$D$12:$D$14";
  1187. int namedCellIdx = wb.getNameIndex(cellName);
  1188. Name aNamedCell = wb.getNameAt(namedCellIdx);
  1189. // Retrieve the cell at the named range and test its contents
  1190. // Will get back one AreaReference for C10, and
  1191. // another for D12 to D14
  1192. AreaReference[] arefs = AreaReference.generateContiguous(aNamedCell.getRefersToFormula());
  1193. for (int i=0; i&lt;arefs.length; i++) {
  1194. // Only get the corners of the Area
  1195. // (use arefs[i].getAllReferencedCells() to get all cells)
  1196. CellReference[] crefs = arefs[i].getCells();
  1197. for (int j=0; j&lt;crefs.length; j++) {
  1198. // Check it turns into real stuff
  1199. Sheet s = wb.getSheet(crefs[j].getSheetName());
  1200. Row r = s.getRow(crefs[j].getRow());
  1201. Cell c = r.getCell(crefs[j].getCol());
  1202. // Do something with this corner cell
  1203. }
  1204. }
  1205. </source>
  1206. <p>
  1207. Note, when a cell is deleted, Excel does not delete the
  1208. attached named range. As result, workbook can contain
  1209. named ranges that point to cells that no longer exist.
  1210. You should check the validity of a reference before
  1211. constructing AreaReference
  1212. </p>
  1213. <source>
  1214. if(name.isDeleted()){
  1215. //named range points to a deleted cell.
  1216. } else {
  1217. AreaReference ref = new AreaReference(name.getRefersToFormula());
  1218. }
  1219. </source>
  1220. </section>
  1221. <anchor id="CellComments"/>
  1222. <section><title>Cell Comments - HSSF and XSSF</title>
  1223. <p>
  1224. A comment is a rich text note that is attached to &amp;
  1225. associated with a cell, separate from other cell content.
  1226. Comment content is stored separate from the cell, and is displayed in a drawing object (like a text box)
  1227. that is separate from, but associated with, a cell
  1228. </p>
  1229. <source>
  1230. Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
  1231. CreationHelper factory = wb.getCreationHelper();
  1232. Sheet sheet = wb.createSheet();
  1233. Rowl row = sheet.createRow(3);
  1234. Cell cell = row.createCell(5);
  1235. cell.setCellValue("F4");
  1236. Drawing drawing = sheet.createDrawingPatriarch();
  1237. // When the comment box is visible, have it show in a 1x3 space
  1238. ClientAnchor anchor = factory.createClientAnchor();
  1239. anchor.setCol1(cell.getColumnIndex());
  1240. anchor.setCol2(cell.getColumnIndex()+1);
  1241. anchor.setRow1(row.getRowNul());
  1242. anchor.setRow2(row.getRowNul()+3);
  1243. // Create the comment and set the text+author
  1244. Comment comment = drawing.createCellComment(anchor);
  1245. RichTextString str = factory.createRichTextString("Hello, World!");
  1246. comment.setString(str);
  1247. comment.setAuthor("Apache POI");
  1248. // Assign the comment to the cell
  1249. cell.setCellComment(comment);
  1250. String fname = "comment-xssf.xls";
  1251. if(wb instanceof XSSFWorkbook) fname += "x";
  1252. FileOutputStream out = new FileOutputStream(fname);
  1253. wb.write(out);
  1254. out.close();
  1255. </source>
  1256. <p>
  1257. Reading cell comments
  1258. </p>
  1259. <source>
  1260. Cell cell = sheet.get(3).getColumn((short)1);
  1261. Comment comment = cell.getCellComment();
  1262. if (comment != null) {
  1263. RichTextString str = comment.getString();
  1264. String author = comment.getAuthor();
  1265. }
  1266. // alternatively you can retrieve cell comments by (row, column)
  1267. comment = sheet.getCellComment(3, 1);
  1268. </source>
  1269. </section>
  1270. <anchor id="Autofit"/>
  1271. <section><title>Adjust column width to fit the contents</title>
  1272. <source>
  1273. Sheet sheet = workbook.getSheetAt(0);
  1274. sheet.autoSizeColumn(0); //adjust width of the first column
  1275. sheet.autoSizeColumn(1); //adjust width of the second column
  1276. </source>
  1277. <p>
  1278. Note, that Sheet#autoSizeColumn() does not evaluate formula cells,
  1279. the width of formula cells is calculated based on the cached formula result.
  1280. If your workbook has many formulas then it is a good idea to evaluate them before auto-sizing.
  1281. </p>
  1282. <warning>
  1283. To calculate column width Sheet.autoSizeColumn uses Java2D classes
  1284. that throw exception if graphical environment is not available. In case if graphical environment
  1285. is not available, you must tell Java that you are running in headless mode and
  1286. set the following system property: <code> java.awt.headless=true </code>.
  1287. </warning>
  1288. </section>
  1289. <anchor id="Hyperlinks"/>
  1290. <section><title>How to read hyperlinks</title>
  1291. <source>
  1292. Sheet sheet = workbook.getSheetAt(0);
  1293. Cell cell = sheet.getRow(0).getCell((short)0);
  1294. Hyperlink link = cell.getHyperlink();
  1295. if(link != null){
  1296. System.out.println(link.getAddress());
  1297. }
  1298. </source>
  1299. </section>
  1300. <section><title>How to create hyperlinks</title>
  1301. <source>
  1302. Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
  1303. CreationHelper createHelper = wb.getCreationHelper();
  1304. //cell style for hyperlinks
  1305. //by default hyperlinks are blue and underlined
  1306. CellStyle hlink_style = wb.createCellStyle();
  1307. Font hlink_font = wb.createFont();
  1308. hlink_font.setUnderline(Font.U_SINGLE);
  1309. hlink_font.setColor(IndexedColors.BLUE.getIndex());
  1310. hlink_style.setFont(hlink_font);
  1311. Cell cell;
  1312. Sheet sheet = wb.createSheet("Hyperlinks");
  1313. //URL
  1314. cell = sheet.createRow(0).createCell((short)0);
  1315. cell.setCellValue("URL Link");
  1316. Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
  1317. link.setAddress("http://poi.apache.org/");
  1318. cell.setHyperlink(link);
  1319. cell.setCellStyle(hlink_style);
  1320. //link to a file in the current directory
  1321. cell = sheet.createRow(1).createCell((short)0);
  1322. cell.setCellValue("File Link");
  1323. link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
  1324. link.setAddress("link1.xls");
  1325. cell.setHyperlink(link);
  1326. cell.setCellStyle(hlink_style);
  1327. //e-mail link
  1328. cell = sheet.createRow(2).createCell((short)0);
  1329. cell.setCellValue("Email Link");
  1330. link = createHelper.createHyperlink(Hyperlink.LINK_EMAIL);
  1331. //note, if subject contains white spaces, make sure they are url-encoded
  1332. link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
  1333. cell.setHyperlink(link);
  1334. cell.setCellStyle(hlink_style);
  1335. //link to a place in this workbook
  1336. //create a target sheet and cell
  1337. Sheet sheet2 = wb.createSheet("Target Sheet");
  1338. sheet2.createRow(0).createCell((short)0).setCellValue("Target Cell");
  1339. cell = sheet.createRow(3).createCell((short)0);
  1340. cell.setCellValue("Worksheet Link");
  1341. Hyperlink link2 = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
  1342. link2.setAddress("'Target Sheet'!A1");
  1343. cell.setHyperlink(link2);
  1344. cell.setCellStyle(hlink_style);
  1345. FileOutputStream out = new FileOutputStream("hyperinks.xlsx");
  1346. wb.write(out);
  1347. out.close();
  1348. </source>
  1349. </section>
  1350. <anchor id="Validation"/>
  1351. <section><title>Data Validations</title>
  1352. <p>
  1353. As of version 3.8, POI has slightly different syntax to work with data validations with .xls and .xlsx formats.
  1354. </p>
  1355. <section>
  1356. <title>hssf.usermodel (binary .xls format)</title>
  1357. <p><strong>Check the value a user enters into a cell against one or more predefined value(s).</strong></p>
  1358. <p>The following code will limit the value the user can enter into cell A1 to one of three integer values, 10, 20 or 30.</p>
  1359. <source>
  1360. HSSFWorkbook workbook = new HSSFWorkbook();
  1361. HSSFSheet sheet = workbook.createSheet("Data Validation");
  1362. CellRangeAddressList addressList = new CellRangeAddressList(
  1363. 0, 0, 0, 0);
  1364. DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(
  1365. new String[]{"10", "20", "30"});
  1366. DataValidation dataValidation = new HSSFDataValidation
  1367. (addressList, dvConstraint);
  1368. dataValidation.setSuppressDropDownArrow(true);
  1369. sheet.addValidationData(dataValidation);
  1370. </source>
  1371. <p><strong> Drop Down Lists:</strong></p>
  1372. <p>This code will do the same but offer the user a drop down list to select a value from.</p>
  1373. <source>
  1374. HSSFWorkbook workbook = new HSSFWorkbook();
  1375. HSSFSheet sheet = workbook.createSheet("Data Validation");
  1376. CellRangeAddressList addressList = new CellRangeAddressList(
  1377. 0, 0, 0, 0);
  1378. DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(
  1379. new String[]{"10", "20", "30"});
  1380. DataValidation dataValidation = new HSSFDataValidation
  1381. (addressList, dvConstraint);
  1382. dataValidation.setSuppressDropDownArrow(false);
  1383. sheet.addValidationData(dataValidation);
  1384. </source>
  1385. <p><strong>Messages On Error:</strong></p>
  1386. <p>To create a message box that will be shown to the user if the value they enter is invalid.</p>
  1387. <source>
  1388. dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
  1389. dataValidation.createErrorBox("Box Title", "Message Text");
  1390. </source>
  1391. <p>Replace 'Box Title' with the text you wish to display in the message box's title bar
  1392. and 'Message Text' with the text of your error message.</p>
  1393. <p><strong>Prompts:</strong></p>
  1394. <p>To create a prompt that the user will see when the cell containing the data validation receives focus</p>
  1395. <source>
  1396. dataValidation.createPromptBox("Title", "Message Text");
  1397. dataValidation.setShowPromptBox(true);
  1398. </source>
  1399. <p>The text encapsulated in the first parameter passed to the createPromptBox() method will appear emboldened
  1400. and as a title to the prompt whilst the second will be displayed as the text of the message.
  1401. The createExplicitListConstraint() method can be passed and array of String(s) containing interger, floating point, dates or text values.</p>
  1402. <p><strong>Further Data Validations:</strong></p>
  1403. <p>To obtain a validation that would check the value entered was, for example, an integer between 10 and 100,
  1404. use the DVConstraint.createNumericConstraint(int, int, String, String) factory method.</p>
  1405. <source>
  1406. dvConstraint = DVConstraint.createNumericConstraint(
  1407. DVConstraint.ValidationType.INTEGER,
  1408. DVConstraint.OperatorType.BETWEEN, "10", "100");
  1409. </source>
  1410. <p>Look at the javadoc for the other validation and operator types; also note that not all validation
  1411. types are supported for this method. The values passed to the two String parameters can be formulas; the '=' symbol is used to denote a formula</p>
  1412. <source>
  1413. dvConstraint = DVConstraint.createNumericConstraint(
  1414. DVConstraint.ValidationType.INTEGER,
  1415. DVConstraint.OperatorType.BETWEEN, "=SUM(A1:A3)", "100");
  1416. </source>
  1417. <p>It is not possible to create a drop down list if the createNumericConstraint() method is called,
  1418. the setSuppressDropDownArrow(false) method call will simply be ignored.</p>
  1419. <p>Date and time constraints can be created by calling the createDateConstraint(int, String, String, String)
  1420. or the createTimeConstraint(int, String, String). Both are very similar to the above and are explained in the javadoc. </p>
  1421. <p><strong>Creating Data Validations From Spreadsheet Cells.</strong></p>
  1422. <p>The contents of specific cells can be used to provide the values for the data validation
  1423. and the DVConstraint.createFormulaListConstraint(String) method supports this.
  1424. To specify that the values come from a contiguous range of cells do either of the following:</p>
  1425. <source>
  1426. dvConstraint = DVConstraint.createFormulaListConstraint("$A$1:$A$3");
  1427. </source>
  1428. <p>or</p>
  1429. <source>
  1430. Name namedRange = workbook.createName();
  1431. namedRange.setNameName("list1");
  1432. namedRange.setRefersToFormula("$A$1:$A$3");
  1433. dvConstraint = DVConstraint.createFormulaListConstraint("list1");
  1434. </source>
  1435. <p>and in both cases the user will be able to select from a drop down list containing the values from cells A1, A2 and A3.</p>
  1436. <p>The data does not have to be as the data validation. To select the data from a different sheet however, the sheet
  1437. must be given a name when created and that name should be used in the formula. So assuming the existence of a sheet named 'Data Sheet' this will work:</p>
  1438. <source>
  1439. Name namedRange = workbook.createName();
  1440. namedRange.setNameName("list1");
  1441. namedRange.setRefersToFormula("'Data Sheet'!$A$1:$A$3");
  1442. dvConstraint = DVConstraint.createFormulaListConstraint("list1");
  1443. </source>
  1444. <p>as will this:</p>
  1445. <source>
  1446. dvConstraint = DVConstraint.createFormulaListConstraint("'Data Sheet'!$A$1:$A$3");
  1447. </source>
  1448. <p>whilst this will not:</p>
  1449. <source>
  1450. Name namedRange = workbook.createName();
  1451. namedRange.setNameName("list1");
  1452. namedRange.setRefersToFormula("'Sheet1'!$A$1:$A$3");
  1453. dvConstraint = DVConstraint.createFormulaListConstraint("list1");
  1454. </source><p>and nor will this:</p><source>
  1455. dvConstraint = DVConstraint.createFormulaListConstraint("'Sheet1'!$A$1:$A$3");
  1456. </source>
  1457. </section>
  1458. <section>
  1459. <title>xssf.usermodel (.xlsx format)</title>
  1460. <p>
  1461. Data validations work similarly when you are creating an xml based, SpreadsheetML,
  1462. workbook file; but there are differences. Explicit casts are required, for example,
  1463. in a few places as much of the support for data validations in the xssf stream was
  1464. built into the unifying ss stream, of which more later. Other differences are
  1465. noted with comments in the code.
  1466. </p>
  1467. <p><strong>Check the value the user enters into a cell against one or more predefined value(s).</strong></p>
  1468. <source>
  1469. XSSFWorkbook workbook = new XSSFWorkbook();
  1470. XSSFSheet sheet = workbook.createSheet("Data Validation");
  1471. XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
  1472. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
  1473. dvHelper.createExplicitListConstraint(new String[]{"11", "21", "31"});
  1474. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
  1475. XSSFDataValidation validation =(XSSFDataValidation)dvHelper.createValidation(
  1476. dvConstraint, addressList);
  1477. // Here the boolean value false is passed to the setSuppressDropDownArrow()
  1478. // method. In the hssf.usermodel examples above, the value passed to this
  1479. // method is true.
  1480. validation.setSuppressDropDownArrow(false);
  1481. // Note this extra method call. If this method call is omitted, or if the
  1482. // boolean value false is passed, then Excel will not validate the value the
  1483. // user enters into the cell.
  1484. validation.setShowErrorBox(true);
  1485. sheet.addValidationData(validation);
  1486. </source>
  1487. <p><strong>Drop Down Lists:</strong></p>
  1488. <p>This code will do the same but offer the user a drop down list to select a value from.</p>
  1489. <source>
  1490. XSSFWorkbook workbook = new XSSFWorkbook();
  1491. XSSFSheet sheet = workbook.createSheet("Data Validation");
  1492. XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
  1493. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
  1494. dvHelper.createExplicitListConstraint(new String[]{"11", "21", "31"});
  1495. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
  1496. XSSFDataValidation validation = (XSSFDataValidation)dvHelper.createValidation(
  1497. dvConstraint, addressList);
  1498. validation.setShowErrorBox(true);
  1499. sheet.addValidationData(validation);
  1500. </source>
  1501. <p>Note that the call to the setSuppressDropDowmArrow() method can either be simply excluded or replaced with:</p>
  1502. <source>
  1503. validation.setSuppressDropDownArrow(true);
  1504. </source>
  1505. <p><strong>Prompts and Error Messages:</strong></p>
  1506. <p>
  1507. These both exactly mirror the hssf.usermodel so please refer to the 'Messages On Error:' and 'Prompts:' sections above.
  1508. </p>
  1509. <p><strong>Further Data Validations:</strong></p>
  1510. <p>
  1511. To obtain a validation that would check the value entered was, for example,
  1512. an integer between 10 and 100, use the XSSFDataValidationHelper(s) createNumericConstraint(int, int, String, String) factory method.
  1513. </p>
  1514. <source>
  1515. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
  1516. dvHelper.createNumericConstraint(
  1517. XSSFDataValidationConstraint.ValidationType.INTEGER,
  1518. XSSFDataValidationConstraint.OperatorType.BETWEEN,
  1519. "10", "100");
  1520. </source>
  1521. <p>
  1522. The values passed to the final two String parameters can be formulas; the '=' symbol is used to denote a formula.
  1523. Thus, the following would create a validation the allows values only if they fall between the results of summing two cell ranges
  1524. </p>
  1525. <source>
  1526. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
  1527. dvHelper.createNumericConstraint(
  1528. XSSFDataValidationConstraint.ValidationType.INTEGER,
  1529. XSSFDataValidationConstraint.OperatorType.BETWEEN,
  1530. "=SUM(A1:A10)", "=SUM(B24:B27)");
  1531. </source>
  1532. <p>
  1533. It is not possible to create a drop down list if the createNumericConstraint() method is called,
  1534. the setSuppressDropDownArrow(true) method call will simply be ignored.
  1535. </p>
  1536. <p>
  1537. Please check the javadoc for other constraint types as examples for those will not be included here.
  1538. There are, for example, methods defined on the XSSFDataValidationHelper class allowing you to create
  1539. the following types of constraint; date, time, decimal, integer, numeric, formula, text length and custom constraints.
  1540. </p>
  1541. <p><strong>Creating Data Validations From Spread Sheet Cells:</strong></p>
  1542. <p>
  1543. One other type of constraint not mentioned above is the formula list constraint.
  1544. It allows you to create a validation that takes it value(s) from a range of cells. This code
  1545. </p>
  1546. <source>
  1547. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
  1548. dvHelper.createFormulaListConstraint("$A$1:$F$1");
  1549. </source>
  1550. <p>
  1551. would create a validation that took it's values from cells in the range A1 to F1.
  1552. </p>
  1553. <p>
  1554. The usefulness of this technique can be extended if you use named ranges like this;
  1555. </p>
  1556. <source>
  1557. XSSFName name = workbook.createName();
  1558. name.setNameName("data");
  1559. name.setRefersToFormula("$B$1:$F$1");
  1560. XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
  1561. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
  1562. dvHelper.createFormulaListConstraint("data");
  1563. CellRangeAddressList addressList = new CellRangeAddressList(
  1564. 0, 0, 0, 0);
  1565. XSSFDataValidation validation = (XSSFDataValidation)
  1566. dvHelper.createValidation(dvConstraint, addressList);
  1567. validation.setSuppressDropDownArrow(true);
  1568. validation.setShowErrorBox(true);
  1569. sheet.addValidationData(validation);
  1570. </source>
  1571. <p>
  1572. OpenOffice Calc has slightly different rules with regard to the scope of names.
  1573. Excel supports both Workbook and Sheet scope for a name but Calc does not, it seems only to support Sheet scope for a name.
  1574. Thus it is often best to fully qualify the name for the region or area something like this;
  1575. </p>
  1576. <source>
  1577. XSSFName name = workbook.createName();
  1578. name.setNameName("data");
  1579. name.setRefersToFormula("'Data Validation'!$B$1:$F$1");
  1580. ....
  1581. </source>
  1582. <p>
  1583. This does open a further, interesting opportunity however and that is to place all of the data for the validation(s) into named ranges of cells on a hidden sheet within the workbook. These ranges can then be explicitly identified in the setRefersToFormula() method argument.
  1584. </p>
  1585. </section>
  1586. <section><title>ss.usermodel</title>
  1587. <p>
  1588. The classes within the ss.usermodel package allow developers to create code that can be used
  1589. to generate both binary (.xls) and SpreadsheetML (.xlsx) workbooks.
  1590. </p>
  1591. <p>
  1592. The techniques used to create data validations share much in common with the xssf.usermodel examples above.
  1593. As a result just one or two examples will be presented here.
  1594. </p>
  1595. <p><strong>Check the value the user enters into a cell against one or more predefined value(s).</strong></p>
  1596. <source>
  1597. Workbook workbook = new XSSFWorkbook(); // or new HSSFWorkbook
  1598. Sheet sheet = workbook.createSheet("Data Validation");
  1599. DataValidationHelper dvHelper = sheet.getDataValidationHelper();
  1600. DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(
  1601. new String[]{"13", "23", "33"});
  1602. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
  1603. DataValidation validation = dvHelper.createValidation(
  1604. dvConstraint, addressList);
  1605. // Note the check on the actual type of the DataValidation object.
  1606. // If it is an instance of the XSSFDataValidation class then the
  1607. // boolean value 'false' must be passed to the setSuppressDropDownArrow()
  1608. // method and an explicit call made to the setShowErrorBox() method.
  1609. if(validation instanceof XSSFDataValidation) {
  1610. validation.setSuppressDropDownArrow(false);
  1611. validation.setShowErrorBox(true);
  1612. }
  1613. else {
  1614. // If the Datavalidation contains an instance of the HSSFDataValidation
  1615. // class then 'true' should be passed to the setSuppressDropDownArrow()
  1616. // method and the call to setShowErrorBox() is not necessary.
  1617. validation.setSuppressDropDownArrow(true);
  1618. }
  1619. sheet.addValidationData(validation);
  1620. </source>
  1621. <p><strong>Drop Down Lists:</strong></p>
  1622. <p>This code will do the same but offer the user a drop down list to select a value from.</p>
  1623. <source>
  1624. Workbook workbook = new XSSFWorkbook(); // or new HSSFWorkbook
  1625. Sheet sheet = workbook.createSheet("Data Validation");
  1626. DataValidationHelper dvHelper = sheet.getDataValidationHelper();
  1627. DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(
  1628. new String[]{"13", "23", "33"});
  1629. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
  1630. DataValidation validation = dvHelper.createValidation(
  1631. dvConstraint, addressList);
  1632. // Note the check on the actual type of the DataValidation object.
  1633. // If it is an instance of the XSSFDataValidation class then the
  1634. // boolean value 'false' must be passed to the setSuppressDropDownArrow()
  1635. // method and an explicit call made to the setShowErrorBox() method.
  1636. if(validation instanceof XSSFDataValidation) {
  1637. validation.setSuppressDropDownArrow(true);
  1638. validation.setShowErrorBox(true);
  1639. }
  1640. else {
  1641. // If the Datavalidation contains an instance of the HSSFDataValidation
  1642. // class then 'true' should be passed to the setSuppressDropDownArrow()
  1643. // method and the call to setShowErrorBox() is not necessary.
  1644. validation.setSuppressDropDownArrow(false);
  1645. }
  1646. sheet.addValidationData(validation);
  1647. </source>
  1648. <p><strong>Prompts and Error Messages:</strong></p>
  1649. <p>
  1650. These both exactly mirror the hssf.usermodel so please refer to the 'Messages On Error:' and 'Prompts:' sections above.
  1651. </p>
  1652. <p>
  1653. As the differences between the ss.usermodel and xssf.usermodel examples are small -
  1654. restricted largely to the way the DataValidationHelper is obtained, the lack of any
  1655. need to explicitly cast data types and the small difference in behaviour between
  1656. the hssf and xssf interpretation of the setSuppressDropDowmArrow() method,
  1657. no further examples will be included in this section.
  1658. </p>
  1659. <p><strong>Advanced Data Validations.</strong></p>
  1660. <p><strong>Dependent Drop Down Lists.</strong></p>
  1661. <p>
  1662. In some cases, it may be necessary to present to the user a sheet which contains more than one drop down list.
  1663. Further, the choice the user makes in one drop down list may affect the options that are presented to them in
  1664. the second or subsequent drop down lists. One technique that may be used to implement this behaviour will now be explained.
  1665. </p>
  1666. <p>
  1667. There are two keys to the technique; one is to use named areas or regions of cells to hold the data for the drop down lists,
  1668. the second is to use the INDIRECT() function to convert between the name and the actual addresses of the cells.
  1669. In the example section there is a complete working example- called LinkedDropDownLists.java -
  1670. that demonstrates how to create linked or dependent drop down lists. Only the more relevant points are explained here.
  1671. </p>
  1672. <p>
  1673. To create two drop down lists where the options shown in the second depend upon the selection made in the first,
  1674. begin by creating a named region of cells to hold all of the data for populating the first drop down list.
  1675. Next, create a data validation that will look to this named area for its data, something like this;
  1676. </p>
  1677. <source>
  1678. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
  1679. DataValidationHelper dvHelper = sheet.getDataValidationHelper();
  1680. DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint(
  1681. "CHOICES");
  1682. DataValidation validation = dvHelper.createValidation(
  1683. dvConstraint, addressList);
  1684. sheet.addValidationData(validation);
  1685. </source>
  1686. <p>
  1687. Note that the name of the area - in the example above it is 'CHOICES' -
  1688. is simply passed to the createFormulaListConstraint() method. This is sufficient
  1689. to cause Excel to populate the drop down list with data from that named region.
  1690. </p>
  1691. <p>
  1692. Next, for each of the options the user could select in the first drop down list,
  1693. create a matching named region of cells. The name of that region should match the
  1694. text the user could select in the first drop down list. Note, in the example,
  1695. all upper case letters are used in the names of the regions of cells.
  1696. </p>
  1697. <p>
  1698. Now, very similar code can be used to create a second, linked, drop down list;
  1699. </p>
  1700. <source>
  1701. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 1, 1);
  1702. DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint(
  1703. "INDIRECT(UPPER($A$1))");
  1704. DataValidation validation = dvHelper.createValidation(
  1705. dvConstraint, addressList);
  1706. sheet.addValidationData(validation);
  1707. </source>
  1708. <p>
  1709. The key here is in the following Excel function - INDIRECT(UPPER($A$1)) - which is used to populate the second,
  1710. linked, drop down list. Working from the inner-most pair of brackets, it instructs Excel to look
  1711. at the contents of cell A1, to convert what it reads there into upper case – as upper case letters are used
  1712. in the names of each region - and then convert this name into the addresses of those cells that contain
  1713. the data to populate another drop down list.
  1714. </p>
  1715. </section>
  1716. </section>
  1717. <anchor id="Embedded"/>
  1718. <section><title>Embedded Objects</title>
  1719. <p>It is possible to perform more detailed processing of an embedded Excel, Word or PowerPoint document,
  1720. or to work with any other type of embedded object.</p>
  1721. <p><strong>HSSF:</strong></p>
  1722. <source>
  1723. POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("excel_with_embeded.xls"));
  1724. HSSFWorkbook workbook = new HSSFWorkbook(fs);
  1725. for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
  1726. //the OLE2 Class Name of the object
  1727. String oleName = obj.getOLE2ClassName();
  1728. if (oleName.equals("Worksheet")) {
  1729. DirectoryNode dn = (DirectoryNode) obj.getDirectory();
  1730. HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false);
  1731. //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets());
  1732. } else if (oleName.equals("Document")) {
  1733. DirectoryNode dn = (DirectoryNode) obj.getDirectory();
  1734. HWPFDocument embeddedWordDocument = new HWPFDocument(dn, fs);
  1735. //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text());
  1736. } else if (oleName.equals("Presentation")) {
  1737. DirectoryNode dn = (DirectoryNode) obj.getDirectory();
  1738. SlideShow embeddedPowerPointDocument = new SlideShow(new HSLFSlideShow(dn, fs));
  1739. //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length);
  1740. } else {
  1741. if(obj.hasDirectoryEntry()){
  1742. // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
  1743. DirectoryNode dn = (DirectoryNode) obj.getDirectory();
  1744. for (Iterator entries = dn.getEntries(); entries.hasNext();) {
  1745. Entry entry = (Entry) entries.next();
  1746. //System.out.println(oleName + "." + entry.getName());
  1747. }
  1748. } else {
  1749. // There is no DirectoryEntry
  1750. // Recover the object's data from the HSSFObjectData instance.
  1751. byte[] objectData = obj.getObjectData();
  1752. }
  1753. }
  1754. }
  1755. </source>
  1756. <p><strong>XSSF:</strong></p>
  1757. <source>
  1758. XSSFWorkbook workbook = new XSSFWorkbook("excel_with_embeded.xlsx");
  1759. for (PackagePart pPart : workbook.getAllEmbedds()) {
  1760. String contentType = pPart.getContentType();
  1761. // Excel Workbook - either binary or OpenXML
  1762. if (contentType.equals("application/vnd.ms-excel")) {
  1763. HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
  1764. }
  1765. // Excel Workbook - OpenXML file format
  1766. else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
  1767. OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
  1768. XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(docPackage);
  1769. }
  1770. // Word Document - binary (OLE2CDF) file format
  1771. else if (contentType.equals("application/msword")) {
  1772. HWPFDocument document = new HWPFDocument(pPart.getInputStream());
  1773. }
  1774. // Word Document - OpenXML file format
  1775. else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
  1776. OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
  1777. XWPFDocument document = new XWPFDocument(docPackage);
  1778. }
  1779. // PowerPoint Document - binary file format
  1780. else if (contentType.equals("application/vnd.ms-powerpoint")) {
  1781. HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream());
  1782. }
  1783. // PowerPoint Document - OpenXML file format
  1784. else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
  1785. OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
  1786. XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);
  1787. }
  1788. // Any other type of embedded object.
  1789. else {
  1790. System.out.println("Unknown Embedded Document: " + contentType);
  1791. InputStream inputStream = pPart.getInputStream();
  1792. }
  1793. }
  1794. </source>
  1795. </section>
  1796. <anchor id="Autofilter"/>
  1797. <p>(Since POI-3.7)</p>
  1798. <section><title>Autofilters</title>
  1799. <source>
  1800. Workbook wb = new HSSFWorkbook(); //or new XSSFWorkbook();
  1801. Sheet sheet = wb.createSheet();
  1802. sheet.setAutoFilter(CellRangeAddress.valueOf("C5:F200"));
  1803. </source>
  1804. </section>
  1805. <anchor id="ConditionalFormatting"/>
  1806. <section><title>Conditional Formatting</title>
  1807. <source>
  1808. Workbook workbook = new HSSFWorkbook(); // or new XSSFWorkbook();
  1809. Sheet sheet = workbook.createSheet();
  1810. SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
  1811. ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.EQUAL, "0");
  1812. FontFormatting fontFmt = rule1.createFontFormatting();
  1813. fontFmt.setFontStyle(true, false);
  1814. fontFmt.setFontColorIndex(IndexedColors.DARK_RED.index);
  1815. BorderFormatting bordFmt = rule1.createBorderFormatting();
  1816. bordFmt.setBorderBottom(BorderFormatting.BORDER_THIN);
  1817. bordFmt.setBorderTop(BorderFormatting.BORDER_THICK);
  1818. bordFmt.setBorderLeft(BorderFormatting.BORDER_DASHED);
  1819. bordFmt.setBorderRight(BorderFormatting.BORDER_DOTTED);
  1820. PatternFormatting patternFmt = rule1.createPatternFormatting();
  1821. patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index);
  1822. ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.BETWEEN, "-10", "10");
  1823. ConditionalFormattingRule [] cfRules =
  1824. {
  1825. rule1, rule2
  1826. };
  1827. CellRangeAddress[] regions = {
  1828. CellRangeAddress.valueOf("A3:A5")
  1829. };
  1830. sheetCF.addConditionalFormatting(regions, cfRules);
  1831. </source>
  1832. <p> See more examples on Excel conditional formatting in
  1833. <link href="http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java">ConditionalFormats.java</link>
  1834. </p>
  1835. </section>
  1836. <anchor id="Hiding"/>
  1837. <section><title>Hiding and Un-Hiding Rows</title>
  1838. <p>
  1839. Using Excel, it is possible to hide a row on a worksheet by selecting that row (or rows),
  1840. right clicking once on the right hand mouse button and selecting 'Hide' from the pop=up menu that appears.
  1841. </p>
  1842. <p>
  1843. To emulate this using POI, simply call the setZeroHeight() method on an instance of either
  1844. XSSFRow or HSSFRow (the method is defined on the ss.usermodel.Row interface that both classes implement), like this:
  1845. </p>
  1846. <source>
  1847. Workbook workbook = new XSSFWorkbook(); // OR new HSSFWorkbook()
  1848. Sheet sheet = workbook.createSheet(0);
  1849. Row row = workbook.createRow(0);
  1850. row.setZeroHeight();
  1851. </source>
  1852. <p>
  1853. If the file were saved away to disc now, then the first row on the first sheet would not be visible.
  1854. </p>
  1855. <p>
  1856. Using Excel, it is possible to unhide previously hidden rows by selecting the row above and the row below
  1857. the one that is hidden and then pressing and holding down the Ctrl key, the Shift and the pressing
  1858. the number 9 before releasing them all.
  1859. </p>
  1860. <p>
  1861. To emulate this behaviour using POI do something like this:
  1862. </p>
  1863. <source>
  1864. Workbook workbook = WorkbookFactory.create(new File(.......));
  1865. Sheet = workbook.getSheetAt(0);
  1866. Iterator&lt;Row&gt; row Iter = sheet.iterator();
  1867. while(rowIter.hasNext()) {
  1868. Row row = rowIter.next();
  1869. if(row.getZeroHeight()) {
  1870. row.setZeroHeight(false);
  1871. }
  1872. }
  1873. </source>
  1874. <p>
  1875. If the file were saved away to disc now, any previously hidden rows on the first sheet of the workbook would now be visible.
  1876. </p>
  1877. <p>
  1878. The example illustrates two features. Firstly, that it is possible to unhide a row simply by calling the setZeroHeight()
  1879. method and passing the boolean value 'false'. Secondly, it ilustrates how to test whther a row is hidden or not.
  1880. Simply call the getZeroHeight() method and it will return 'true' if the row is hidden, 'false' otherwise.
  1881. </p>
  1882. </section>
  1883. </body>
  1884. </document>