List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument close
@Override public void close() throws IOException
Once this has been called, no further operations, updates or reads should be performed on the document.
From source file:br.com.techne.gluonsoft.eowexport.builder.WordBuilder.java
License:Apache License
/** * mtodo cria bytes de documento Excel/*from w w w.java2 s .c o m*/ * @param titles * @param columnIndex * @param dataRows * @param locale * @return * @throws Exception */ public static byte[] createStyledTable(String[] titles, String[] columnIndex, List<HashMap<String, Object>> dataRows, Locale locale) throws Exception { // Create a new document from scratch XWPFDocument doc = new XWPFDocument(); byte[] outBytes; try { int nRows = dataRows.size() + 1; int nCols = columnIndex.length == 0 ? dataRows.get(0).keySet().size() : columnIndex.length; XWPFTable table = doc.createTable(nRows, nCols); // Set the table style. If the style is not defined, the table style // will become "Normal". CTTblPr tblPr = table.getCTTbl().getTblPr(); CTString styleStr = tblPr.addNewTblStyle(); styleStr.setVal("StyledTable"); // Get a list of the rows in the table List<XWPFTableRow> rows = table.getRows(); int rowCt = 1; addTitle(rows, titles); ValueCellUtil vcutil = new ValueCellUtil(locale); for (HashMap<String, Object> dataRow : dataRows) { addRow(rows, dataRow, rowCt, vcutil, columnIndex); rowCt++; } // write for return byte[] ByteArrayOutputStream out = new ByteArrayOutputStream(); try { doc.write(out); outBytes = out.toByteArray(); } finally { out.close(); } } finally { doc.close(); } return outBytes; }
From source file:cn.wantedonline.porobot.DataBaseEntity.java
License:Apache License
private static void genDBDictionary(List<DBTableBean> tableBeans) throws IOException { XWPFDocument doc = new XWPFDocument(); String databaseName = "default_database"; for (DBTableBean bean : tableBeans) { databaseName = bean.getDatabaseName(); XWPFParagraph p0 = doc.createParagraph(); p0.setAlignment(ParagraphAlignment.CENTER); XWPFRun r0 = p0.createRun();/*w w w . j a v a2s . c o m*/ r0.setBold(true); r0.setText(databaseName); r0.setFontSize(16); XWPFParagraph p1 = doc.createParagraph(); p1.setAlignment(ParagraphAlignment.LEFT); XWPFRun r1 = p1.createRun(); r1.setBold(true); r1.setText("Table:" + bean.getTableName()); XWPFTable table = doc.createTable(); int pos = 0; XWPFTableRow row1 = table.insertNewTableRow(pos++); XWPFTableCell cell1 = row1.createCell(); cell1.setText("Field"); cell1.setColor("FFE4C4"); XWPFTableCell cell2 = row1.createCell(); cell2.setText("Type"); cell2.setColor("FFE4C4"); XWPFTableCell cell3 = row1.createCell(); cell3.setText("Comment"); cell3.setColor("FFE4C4"); for (int i = 0; i < bean.getColumnSize(); i++) { XWPFTableRow row = table.insertNewTableRow(pos++); XWPFTableCell cell11 = row.createCell(); cell11.setText(bean.getColumnName(i)); XWPFTableCell cell22 = row.createCell(); cell22.setText(bean.getColumnType(i)); XWPFTableCell cell33 = row.createCell(); cell33.setText(bean.getColumnComment(i)); } table.removeRow(pos); XWPFParagraph p2 = doc.createParagraph(); XWPFRun r2 = p2.createRun(); r2.addBreak(); } FileOutputStream out = new FileOutputStream(databaseName + ".docx"); doc.write(out); out.close(); doc.close(); }
From source file:com.example.office.DOCDocumentParse.java
@SuppressWarnings("unused") private File doc2docxOld(File docFile) { String docxFilePath = docFile.getPath() + "x"; File docxFile = new File(docxFilePath); if (!docxFile.exists()) { XWPFDocument document = null; try (InputStream ins = new FileInputStream(docxFile); OutputStream out = new FileOutputStream(docxFile);) { Document doc = new Document(docFile.getPath()); doc.save(docxFile.getPath()); document = new XWPFDocument(ins); // document.removeBodyElement(0) List<IBodyElement> elements = document.getBodyElements(); IBodyElement element = elements.get(elements.size() - 1); if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element.getElementType().name())) { XWPFParagraph xp = ((XWPFParagraph) element); String text = xp.getText(); if (StringUtils.isNotBlank(text)) { if (text.contains("Evaluation") && text.contains("Aspose")) { document.removeBodyElement(elements.size() - 1); }//from ww w . j a v a2s . c om } } IBodyElement element0 = elements.get(0); if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element0.getElementType().name())) { XWPFParagraph xp = ((XWPFParagraph) element0); String text = xp.getText(); if (StringUtils.isNotBlank(text)) { if (text.contains("Evaluation") && text.contains("Aspose")) { document.removeBodyElement(0); } } } document.write(out); } catch (Exception e) { LogUtils.writeWarnExceptionLog(log, e); } finally { try { if (document != null) document.close(); } catch (IOException e) { LogUtils.writeDebugExceptionLog(log, e); } } } return docxFile; }
From source file:com.example.office.DOCDocumentParse.java
private void deleteAsposeInfo(File docxFile) { XWPFDocument document = null; try (InputStream ins = new FileInputStream(docxFile); OutputStream out = new FileOutputStream(docxFile);) { document = new XWPFDocument(ins); List<IBodyElement> elements = document.getBodyElements(); IBodyElement element = elements.get(elements.size() - 1); if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element.getElementType().name())) { XWPFParagraph xp = ((XWPFParagraph) element); String text = xp.getText(); if (StringUtils.isNotBlank(text)) { if (text.contains("Evaluation") && text.contains("Aspose")) { document.removeBodyElement(elements.size() - 1); }// ww w.j a v a2 s . c o m } } IBodyElement element0 = elements.get(0); if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element0.getElementType().name())) { XWPFParagraph xp = ((XWPFParagraph) element0); String text = xp.getText(); if (StringUtils.isNotBlank(text)) { if (text.contains("Evaluation") && text.contains("Aspose")) { document.removeBodyElement(0); } } } document.write(out); } catch (Exception e) { LogUtils.writeWarnExceptionLog(log, e); } finally { if (document != null) { try { document.close(); } catch (IOException e) { LogUtils.writeDebugExceptionLog(log, e); } } } }
From source file:com.glodon.tika.SimpleDocument.java
License:Apache License
public static void main(String[] args) throws Exception { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p1 = doc.createParagraph(); p1.setAlignment(ParagraphAlignment.CENTER); p1.setBorderBottom(Borders.DOUBLE);//ww w .j ava2s .c om p1.setBorderTop(Borders.DOUBLE); p1.setBorderRight(Borders.DOUBLE); p1.setBorderLeft(Borders.DOUBLE); p1.setBorderBetween(Borders.SINGLE); p1.setVerticalAlignment(TextAlignment.TOP); XWPFRun r1 = p1.createRun(); r1.setBold(true); r1.setText("The quick brown fox"); r1.setBold(true); r1.setFontFamily("Courier"); r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); r1.setTextPosition(100); XWPFParagraph p2 = doc.createParagraph(); p2.setAlignment(ParagraphAlignment.RIGHT); //BORDERS p2.setBorderBottom(Borders.DOUBLE); p2.setBorderTop(Borders.DOUBLE); p2.setBorderRight(Borders.DOUBLE); p2.setBorderLeft(Borders.DOUBLE); p2.setBorderBetween(Borders.SINGLE); XWPFRun r2 = p2.createRun(); r2.setText("jumped over the lazy dog"); r2.setStrikeThrough(true); r2.setFontSize(20); XWPFRun r3 = p2.createRun(); r3.setText("and went away"); r3.setStrikeThrough(true); r3.setFontSize(20); r3.setSubscript(VerticalAlign.SUPERSCRIPT); XWPFParagraph p3 = doc.createParagraph(); p3.setWordWrapped(true); p3.setPageBreak(true); //p3.setAlignment(ParagraphAlignment.DISTRIBUTE); p3.setAlignment(ParagraphAlignment.BOTH); p3.setSpacingLineRule(LineSpacingRule.EXACT); p3.setIndentationFirstLine(600); XWPFRun r4 = p3.createRun(); r4.setTextPosition(20); r4.setText("To be, or not to be: that is the question: " + "Whether 'tis nobler in the mind to suffer " + "The slings and arrows of outrageous fortune, " + "Or to take arms against a sea of troubles, " + "And by opposing end them? To die: to sleep; "); r4.addBreak(BreakType.PAGE); r4.setText("No more; and by a sleep to say we end " + "The heart-ache and the thousand natural shocks " + "That flesh is heir to, 'tis a consummation " + "Devoutly to be wish'd. To die, to sleep; " + "To sleep: perchance to dream: ay, there's the rub; " + "......."); r4.setItalic(true); //This would imply that this break shall be treated as a simple line break, and break the line after that word: XWPFRun r5 = p3.createRun(); r5.setTextPosition(-10); r5.setText("For in that sleep of death what dreams may come"); r5.addCarriageReturn(); r5.setText("When we have shuffled off this mortal coil," + "Must give us pause: there's the respect" + "That makes calamity of so long life;"); r5.addBreak(); r5.setText("For who would bear the whips and scorns of time," + "The oppressor's wrong, the proud man's contumely,"); r5.addBreak(BreakClear.ALL); r5.setText("The pangs of despised love, the law's delay," + "The insolence of office and the spurns" + "......."); FileOutputStream out = new FileOutputStream("simple.docx"); doc.write(out); out.close(); doc.close(); }
From source file:com.glodon.tika.SimpleImages.java
License:Apache License
public static void main(String[] args) throws IOException, InvalidFormatException { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.createParagraph(); XWPFRun r = p.createRun();// ww w .ja v a 2 s .c o m for (String imgFile : args) { int format; if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; else if (imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; else { System.err.println("Unsupported picture: " + imgFile + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"); continue; } r.setText(imgFile); r.addBreak(); r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels r.addBreak(BreakType.PAGE); } FileOutputStream out = new FileOutputStream("images.docx"); doc.write(out); out.close(); doc.close(); }
From source file:com.glodon.tika.SimpleTable.java
License:Apache License
public static void createSimpleTable() throws Exception { XWPFDocument doc = new XWPFDocument(); try {//ww w . j a v a2s . co m XWPFTable table = doc.createTable(3, 3); table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE"); // table cells have a list of paragraphs; there is an initial // paragraph created when the cell is created. If you create a // paragraph in the document to put in the cell, it will also // appear in the document following the table, which is probably // not the desired result. XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0); XWPFRun r1 = p1.createRun(); r1.setBold(true); r1.setText("The quick brown fox"); r1.setItalic(true); r1.setFontFamily("Courier"); r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); r1.setTextPosition(100); table.getRow(2).getCell(2).setText("only text"); OutputStream out = new FileOutputStream("simpleTable.docx"); try { doc.write(out); } finally { out.close(); } } finally { doc.close(); } }
From source file:com.glodon.tika.SimpleTable.java
License:Apache License
/** * Create a table with some row and column styling. I "manually" add the * style name to the table, but don't check to see if the style actually * exists in the document. Since I'm creating it from scratch, it obviously * won't exist. When opened in MS Word, the table style becomes "Normal". * I manually set alternating row colors. This could be done using Themes, * but that's left as an exercise for the reader. The cells in the last * column of the table have 10pt. "Courier" font. * I make no claims that this is the "right" way to do it, but it worked * for me. Given the scarcity of XWPF examples, I thought this may prove * instructive and give you ideas for your own solutions. // www.ja v a 2 s .c o m * @throws Exception */ public static void createStyledTable() throws Exception { // Create a new document from scratch XWPFDocument doc = new XWPFDocument(); try { // -- OR -- // open an existing empty document with styles already defined //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx")); // Create a new table with 6 rows and 3 columns int nRows = 6; int nCols = 3; XWPFTable table = doc.createTable(nRows, nCols); // Set the table style. If the style is not defined, the table style // will become "Normal". CTTblPr tblPr = table.getCTTbl().getTblPr(); CTString styleStr = tblPr.addNewTblStyle(); styleStr.setVal("StyledTable"); // Get a list of the rows in the table List<XWPFTableRow> rows = table.getRows(); int rowCt = 0; int colCt = 0; for (XWPFTableRow row : rows) { // get table row properties (trPr) CTTrPr trPr = row.getCtRow().addNewTrPr(); // set row height; units = twentieth of a point, 360 = 0.25" CTHeight ht = trPr.addNewTrHeight(); ht.setVal(BigInteger.valueOf(360)); // get the cells in this row List<XWPFTableCell> cells = row.getTableCells(); // add content to each cell for (XWPFTableCell cell : cells) { // get a table cell properties element (tcPr) CTTcPr tcpr = cell.getCTTc().addNewTcPr(); // set vertical alignment to "center" CTVerticalJc va = tcpr.addNewVAlign(); va.setVal(STVerticalJc.CENTER); // create cell color element CTShd ctshd = tcpr.addNewShd(); ctshd.setColor("auto"); ctshd.setVal(STShd.CLEAR); if (rowCt == 0) { // header row ctshd.setFill("A7BFDE"); } else if (rowCt % 2 == 0) { // even row ctshd.setFill("D3DFEE"); } else { // odd row ctshd.setFill("EDF2F8"); } // get 1st paragraph in cell's paragraph list XWPFParagraph para = cell.getParagraphs().get(0); // create a run to contain the content XWPFRun rh = para.createRun(); // style cell as desired if (colCt == nCols - 1) { // last column is 10pt Courier rh.setFontSize(10); rh.setFontFamily("Courier"); } if (rowCt == 0) { // header row rh.setText("header row, col " + colCt); rh.setBold(true); para.setAlignment(ParagraphAlignment.CENTER); } else { // other rows rh.setText("row " + rowCt + ", col " + colCt); para.setAlignment(ParagraphAlignment.LEFT); } colCt++; } // for cell colCt = 0; rowCt++; } // for row // write the file OutputStream out = new FileOutputStream("styledTable.docx"); try { doc.write(out); } finally { out.close(); } } finally { doc.close(); } }
From source file:eu.modelwriter.ide.ui.command.ExtractTextHandler.java
License:Open Source License
/** * Extracts text from the given .docx {@link IFile}. * // w w w. j a va 2 s. co m * @param file * the .docx {@link IFile} */ private void exctractDocx(final IFile file) { try { FileInputStream fis = new FileInputStream(file.getLocation().toFile()); XWPFDocument docx = new XWPFDocument(fis); XWPFWordExtractor we = new XWPFWordExtractor(docx); final IPath textPath = file.getFullPath().removeFileExtension().addFileExtension("txt"); final IFile textFile = ResourcesPlugin.getWorkspace().getRoot().getFile(textPath); if (textFile.exists()) { textFile.delete(true, new NullProgressMonitor()); } textFile.create(new ByteArrayInputStream(we.getText().getBytes()), true, new NullProgressMonitor()); we.close(); docx.close(); fis.close(); } catch (IOException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, UNABLE_TO_EXTRACT_TEXT_FROM + file.getFullPath(), e)); } catch (CoreException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, UNABLE_TO_EXTRACT_TEXT_FROM + file.getFullPath(), e)); } }
From source file:nl.detoren.ijc.io.OutputIntekenlijst.java
License:Open Source License
public boolean export(Groepen groepen) { try {// ww w .ja v a 2 s .co m logger.log(Level.INFO, "Wedstrijden wegschrijven naar Excel"); FileInputStream file = new FileInputStream("Leeg.docx"); XWPFDocument document = new XWPFDocument(file); XWPFParagraph paragraph = document.getLastParagraph(); setDoubleLineSpacing(paragraph); XWPFRun run = paragraph.createRun(); run.setFontFamily("Courier New"); run.setFontSize(12); String result; result = "Intekenlijst aangemaakt met " + IJCController.c().appTitle + " voor " + IJCController.c().verenigingNaam; run.setText(result); run.addCarriageReturn(); // separate previous text from break for (int i = 0; i < groepen.getAantalGroepen(); ++i) { if (i >= 1) run.addBreak(); Groep groep = groepen.getGroepById(i); result = "Stand na " + groepen.getRonde() + "e ronde, " + groepen.getPeriode(); result += "e periode " + groep.getNaam() + " (" + groep.getSpelers().size() + ")\n"; run.setText(result); run.addBreak(); result = " Naam ini zw rating gespeeld tegen pnt\n"; run.setText(result); run.addBreak(); result = "-----------------------------------------------------------------------\n"; run.setText(result); run.addBreak(); for (Speler s : groep.getSpelers()) { result = s.toPrintableString(false); run.setText(result); run.addBreak(); } if (IJCController.c().exportDoorschuivers) { int ndoor = IJCController.c().bepaalAantalDoorschuiversVolgendeRonde(groep.getNiveau(), groepen.getPeriode(), groepen.getRonde()); if (i - 1 >= 0) { run.setText(IJCController.c().exportDoorschuiversStart + "\n"); run.addBreak(); Groep lager = groepen.getGroepById(i - 1); if (ndoor > 1) { for (int j = 0; j < ndoor; j++) { Speler s = lager.getSpelerByID(j + 1); run.setText(s.toPrintableString(false, true) + "\n"); run.addBreak(); } run.setText(IJCController.c().exportDoorschuiversStop + "\n" + "\n"); } else { // Bij n doorschuiver, alleen doorschuiven als // kampioen Speler s1 = lager.getSpelerByID(1); Speler s2 = lager.getSpelerByID(2); if ((s2 != null) && ((s1.getPunten() - s2.getPunten()) > 4)) { run.setText(s1.toPrintableString(false, true) + "\n"); run.addBreak(); } } } } run.addCarriageReturn(); // separate previous text from break run.addBreak(BreakType.PAGE); } // Close input file file.close(); // Store Excel to new file String dirName = "R" + groepen.getPeriode() + "-" + groepen.getRonde(); new File(dirName).mkdirs(); String filename = dirName + File.separator + "IntekenlijstR" + groepen.getPeriode() + "-" + groepen.getRonde() + ".docx"; File outputFile = new File(filename); FileOutputStream outFile = new FileOutputStream(outputFile); document.write(outFile); // Close output file document.close(); outFile.close(); // And open it in the system editor //Desktop.getDesktop().open(new File(outputFile)); return true; } catch (Exception ex) { logger.log(Level.WARNING, "Export mislukt :" + ex.getMessage()); Utils.stacktrace(ex); return false; } }