You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimpleTable.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.examples.xwpf.usermodel;
  16. import java.io.FileOutputStream;
  17. import java.io.OutputStream;
  18. import java.math.BigInteger;
  19. import java.util.List;
  20. import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
  21. import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
  22. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  23. import org.apache.poi.xwpf.usermodel.XWPFParagraph;
  24. import org.apache.poi.xwpf.usermodel.XWPFRun;
  25. import org.apache.poi.xwpf.usermodel.XWPFTable;
  26. import org.apache.poi.xwpf.usermodel.XWPFTableCell;
  27. import org.apache.poi.xwpf.usermodel.XWPFTableRow;
  28. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight;
  29. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
  30. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;
  31. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
  32. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
  33. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr;
  34. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc;
  35. import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
  36. import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
  37. /**
  38. * This program creates a simple WordprocessingML table using POI XWPF API, and
  39. * a more complex, styled table using both XWPF and poi-ooxml-full. It's possible
  40. * that not all referenced wordprocessingml classes are defined in the
  41. * poi-ooxml-lite jar. If this is the case, you'll need to use the
  42. * poi-ooxml-full jar library.
  43. *
  44. * @author gisella bronzetti (original)
  45. * @author Gregg Morris (styled table)
  46. */
  47. public class SimpleTable {
  48. public static void main(String[] args) throws Exception {
  49. try {
  50. createSimpleTable();
  51. }
  52. catch(Exception e) {
  53. System.out.println("Error trying to create simple table.");
  54. throw(e);
  55. }
  56. try {
  57. createStyledTable();
  58. }
  59. catch(Exception e) {
  60. System.out.println("Error trying to create styled table.");
  61. throw(e);
  62. }
  63. }
  64. public static void createSimpleTable() throws Exception {
  65. try (XWPFDocument doc = new XWPFDocument()) {
  66. XWPFTable table = doc.createTable(3, 3);
  67. table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
  68. // table cells have a list of paragraphs; there is an initial
  69. // paragraph created when the cell is created. If you create a
  70. // paragraph in the document to put in the cell, it will also
  71. // appear in the document following the table, which is probably
  72. // not the desired result.
  73. XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0);
  74. XWPFRun r1 = p1.createRun();
  75. r1.setBold(true);
  76. r1.setText("The quick brown fox");
  77. r1.setItalic(true);
  78. r1.setFontFamily("Courier");
  79. r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
  80. r1.setTextPosition(100);
  81. table.getRow(2).getCell(2).setText("only text");
  82. try (OutputStream out = new FileOutputStream("simpleTable.docx")) {
  83. doc.write(out);
  84. }
  85. }
  86. }
  87. /**
  88. * Create a table with some row and column styling. I "manually" add the
  89. * style name to the table, but don't check to see if the style actually
  90. * exists in the document. Since I'm creating it from scratch, it obviously
  91. * won't exist. When opened in MS Word, the table style becomes "Normal".
  92. * I manually set alternating row colors. This could be done using Themes,
  93. * but that's left as an exercise for the reader. The cells in the last
  94. * column of the table have 10pt. "Courier" font.
  95. * I make no claims that this is the "right" way to do it, but it worked
  96. * for me. Given the scarcity of XWPF examples, I thought this may prove
  97. * instructive and give you ideas for your own solutions.
  98. */
  99. public static void createStyledTable() throws Exception {
  100. // Create a new document from scratch
  101. try (XWPFDocument doc = new XWPFDocument()) {
  102. // -- OR --
  103. // open an existing empty document with styles already defined
  104. //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
  105. // Create a new table with 6 rows and 3 columns
  106. int nRows = 6;
  107. int nCols = 3;
  108. XWPFTable table = doc.createTable(nRows, nCols);
  109. // Set the table style. If the style is not defined, the table style
  110. // will become "Normal".
  111. CTTblPr tblPr = table.getCTTbl().getTblPr();
  112. CTString styleStr = tblPr.addNewTblStyle();
  113. styleStr.setVal("StyledTable");
  114. // Get a list of the rows in the table
  115. List<XWPFTableRow> rows = table.getRows();
  116. int rowCt = 0;
  117. int colCt = 0;
  118. for (XWPFTableRow row : rows) {
  119. // get table row properties (trPr)
  120. CTTrPr trPr = row.getCtRow().addNewTrPr();
  121. // set row height; units = twentieth of a point, 360 = 0.25"
  122. CTHeight ht = trPr.addNewTrHeight();
  123. ht.setVal(BigInteger.valueOf(360));
  124. // get the cells in this row
  125. List<XWPFTableCell> cells = row.getTableCells();
  126. // add content to each cell
  127. for (XWPFTableCell cell : cells) {
  128. // get a table cell properties element (tcPr)
  129. CTTcPr tcpr = cell.getCTTc().addNewTcPr();
  130. // set vertical alignment to "center"
  131. CTVerticalJc va = tcpr.addNewVAlign();
  132. va.setVal(STVerticalJc.CENTER);
  133. // create cell color element
  134. CTShd ctshd = tcpr.addNewShd();
  135. ctshd.setColor("auto");
  136. ctshd.setVal(STShd.CLEAR);
  137. if (rowCt == 0) {
  138. // header row
  139. ctshd.setFill("A7BFDE");
  140. } else if (rowCt % 2 == 0) {
  141. // even row
  142. ctshd.setFill("D3DFEE");
  143. } else {
  144. // odd row
  145. ctshd.setFill("EDF2F8");
  146. }
  147. // get 1st paragraph in cell's paragraph list
  148. XWPFParagraph para = cell.getParagraphs().get(0);
  149. // create a run to contain the content
  150. XWPFRun rh = para.createRun();
  151. // style cell as desired
  152. if (colCt == nCols - 1) {
  153. // last column is 10pt Courier
  154. rh.setFontSize(10);
  155. rh.setFontFamily("Courier");
  156. }
  157. if (rowCt == 0) {
  158. // header row
  159. rh.setText("header row, col " + colCt);
  160. rh.setBold(true);
  161. para.setAlignment(ParagraphAlignment.CENTER);
  162. } else {
  163. // other rows
  164. rh.setText("row " + rowCt + ", col " + colCt);
  165. para.setAlignment(ParagraphAlignment.LEFT);
  166. }
  167. colCt++;
  168. } // for cell
  169. colCt = 0;
  170. rowCt++;
  171. } // for row
  172. // write the file
  173. try (OutputStream out = new FileOutputStream("styledTable.docx")) {
  174. doc.write(out);
  175. }
  176. }
  177. }
  178. }