List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument
public XWPFDocument(InputStream is) throws IOException
From source file:me.philnate.textmanager.utils.WordCount.java
License:Open Source License
/** * opens the given file, if it's a .doc or .docx file and returns the number * of words within the document/*from w w w.j a va2 s .co m*/ * * @param file * @return * @throws FileNotFoundException * @throws IOException */ public static long countFile(File file) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(file.getAbsolutePath())) { if (file.getName().endsWith(".docx")) { XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document); return linecount(extractor.getText()); } else if (file.getName().endsWith(".doc")) { HWPFDocument document = new HWPFDocument(fis); WordExtractor extractor = new WordExtractor(document); return WordCount.linecount(extractor.getText()); } else { throw new IllegalArgumentException("Can't handle non doc(X) files"); } } }
From source file:Modelo.EscribirWord.java
public void cambiarLogo() throws FileNotFoundException, IOException, InvalidFormatException, Exception { //ASPOSE/* w w w . j a v a 2 s .co m*/ // Document doc = new Document("HojaInventarioObjeto.doc"); //// doc.save("Out.pdf"); // HWPFDocument doc = new HWPFDocument(new FileInputStream("HojaInventarioTemplate.doc")); XWPFDocument document = new XWPFDocument(new FileInputStream("HojaInventarioTemplate.docx")); String imageOldName = "logo"; try { // LOG.info("replaceImage: old=" + "logo" + ", new=" + "imagePathNew"); String imagePathNew = "PlayStation_1_Logo.png"; int newImageWidth = 1; int newImageHeight = 2; int imageParagraphPos = -1; XWPFParagraph imageParagraph = null; List<IBodyElement> documentElements = document.getBodyElements(); for (IBodyElement documentElement : documentElements) { imageParagraphPos++; if (documentElement instanceof XWPFParagraph) { imageParagraph = (XWPFParagraph) documentElement; if (imageParagraph != null && imageParagraph.getCTP() != null && imageParagraph.getCTP().toString().trim().indexOf(imageOldName) != -1) { break; } } } if (imageParagraph == null) { throw new Exception("Unable to replace image data due to the exception:\n" + "'" + imageOldName + "' not found in in document."); } ParagraphAlignment oldImageAlignment = imageParagraph.getAlignment(); // remove old image document.removeBodyElement(imageParagraphPos - 1); // now add new image // BELOW LINE WILL CREATE AN IMAGE // PARAGRAPH AT THE END OF THE DOCUMENT. // REMOVE THIS IMAGE PARAGRAPH AFTER // SETTING THE NEW IMAGE AT THE OLD IMAGE POSITION XWPFParagraph newImageParagraph = document.createParagraph(); XWPFRun newImageRun = newImageParagraph.createRun(); //newImageRun.setText(newImageText); newImageParagraph.setAlignment(oldImageAlignment); try (FileInputStream is = new FileInputStream(imagePathNew)) { newImageRun.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imagePathNew, Units.toEMU(newImageWidth), Units.toEMU(newImageHeight)); } // set new image at the old image position document.setParagraph(newImageParagraph, imageParagraphPos); // NOW REMOVE REDUNDANT IMAGE FORM THE END OF DOCUMENT document.removeBodyElement(document.getBodyElements().size() - 1); // return document; } catch (Exception e) { throw new Exception("Unable to replace image '" + imageOldName + "' due to the exception:\n" + e); } finally { // cleanup code } }
From source file:modelo.Lectura.java
private void leerDocx(InputStream docx) { //Se crea un documento que la POI entiende pasandole el stream //instanciamos el obj para extraer contenido pasando el documento try {// w w w. j a v a 2 s.c om XWPFWordExtractor xwpf_we = new XWPFWordExtractor(new XWPFDocument(docx)); setTextoDeDocx(xwpf_we.getText()); } catch (Exception e) { System.out.println("Fallo al leer del archivo.\n" + e.toString() + "Error en archivo" + javax.swing.JOptionPane.ERROR_MESSAGE); } }
From source file:msoffice.ReadWord.java
public static void main(String[] args) { try {/*from ww w.ja va2s . c o m*/ FileInputStream fis = new FileInputStream("H:\\OFICIOTEMPLATE.docx"); XWPFDocument docx = new XWPFDocument(fis); List<XWPFParagraph> paragraphList = docx.getParagraphs(); int nump = paragraphList.size(); System.out.println(nump); for (int x = 0; x < paragraphList.size(); x++) { } for (XWPFParagraph paragraph : paragraphList) { String text = paragraph.getText(); XWPFRun rh = paragraph.createRun(); if (text.contains("unidad")) { text = text.replace("unidad", "CICTE/W-6.a/02.00"); paragraph.removeRun(8); rh.setText(text); } if (text.contains("receptor")) { text = text.replace("receptor", "Gral Brig Jefe del Servicio de Material de Guerra del Ejrcito"); } if (text.contains("asunto")) { text = text.replace("asunto", "Sobre articulo de MG (Armamento) y apoyo de elemento tecnico."); } if (text.contains("referencia")) { text = text.replace("referencia", "Oficio N289/CICTE del 01 julio de 2015."); } if (text.contains("cuerpo")) { text = text.replace("cuerpo", "Tengo el honor de dirigirme a Ud., para manifestarle que en relacin a la solicitud de prestamo de una (01) ametralladora BROWNING Cal .50 y la participacin del elemento tcnico Tco 2da MAM Pacheco Tejada Henry, para las pruebas del vehculo blindado OTORONGO, las cuales se han suspendido y sern reprogramadas.\n" + "Asimismo, se informar de manera oportuna la fecha de realizacin de las pruebas del vehculo blindado OTORONGO, para poder contar con artculo de MG (Armamento) y apoyo de elemento tcnico solicitado.\n" + "Hago propicia la oportunidad para expresarle a Ud. los sentimientos de mi especial consideracin y estima personal."); } System.out.println(text); docx.write(new FileOutputStream("OFICIO.docx")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:msoffice.WriteinTemplate.java
public static void main(String[] args) throws FileNotFoundException, InvalidFormatException, IOException { FileInputStream fis = new FileInputStream("H:\\OFICIOTEMPLATE.docx"); XWPFDocument doc = new XWPFDocument(fis); for (XWPFParagraph p : doc.getParagraphs()) { for (XWPFRun r : p.getRuns()) { //System.out.println(r); String text = r.getText(0); System.out.println(text); if (text.contains("unidad")) { text = text.replace("unidad", "CICTE/W-6.a/02.00"); r.setText(text, 0);/* w w w . java2 s. c o m*/ System.out.println(text); } if (text.contains("#receptor#")) { text = text.replace("#receptor#", "Gral Brig Jefe del Servicio de Material de Guerra del Ejrcito"); r.setText(text, 0); System.out.println(text); } if (text.contains("#asunto#")) { text = text.replace("#asunto#", "Sobre artculo de MG (Armamento) y apoyo de elemento tcnico."); r.setText(text, 0); System.out.println(text); } if (text.contains("#referencia#")) { text = text.replace("#referencia#", "Oficio N289/CICTE del 01 julio de 2015."); r.setText(text, 0); System.out.println(text); } if (text.contains("#cuerpo#")) { text = text.replace("#cuerpo#", "Tengo el honor de dirigirme a Ud., para manifestarle que en relacin a la solicitud de prstamo de una (01) ametralladora BROWNING Cal .50 y la participacin del elemento tcnico Tco 2da MAM Pacheco Tejada Henry, para las pruebas del vehculo blindado OTORONGO, las cuales se han suspendido y sern reprogramadas.\n" + "Asimismo, se informar de manera oportuna la fecha de realizacin de las pruebas del vehculo blindado OTORONGO, para poder contar con artculo de MG (Armamento) y apoyo de elemento tcnico solicitado.\n" + "Hago propicia la oportunidad para expresarle a Ud. los sentimientos de mi especial consideracin y estima personal."); r.setText(text, 0); System.out.println(text); } } } doc.write(new FileOutputStream("output.docx")); }
From source file:myexamples.WordDocsExamples.Test1.java
public static void simpleFileReading() throws IOException { JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println(chooser.getSelectedFile().getName()); FileInputStream fis = new FileInputStream(chooser.getSelectedFile()); XWPFDocument doc = new XWPFDocument(fis); XWPFWordExtractor extract = new XWPFWordExtractor(doc); System.out.println(extract.getText()); }//from www . jav a2 s .c o m }
From source file:myexamples.WordDocsExamples.Test1.java
public static void simplepartsReading() throws IOException { JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println(chooser.getSelectedFile().getName()); FileInputStream fis = new FileInputStream(chooser.getSelectedFile()); XWPFDocument doc = new XWPFDocument(fis); XWPFWordExtractor extract = new XWPFWordExtractor(doc); //System.out.println(extract.getText()); List<XWPFParagraph> pList = doc.getParagraphs(); List<XWPFTable> tList = doc.getTables(); System.out.println("Number of Paragraphs=" + pList.size()); System.out.println("Number of Tables=" + tList.size()); List<XWPFTableRow> rList; List<XWPFTableCell> cList; List<XWPFParagraph> rcpList; int tCount = 0, rCount = 0, cCount = 0, rcpCount = 0, dummCounter = 0; WordReference wordReference = new WordReference(); for (XWPFTable t : tList) { rList = t.getRows();/*from w ww . ja v a 2 s . co m*/ rCount = 0; cCount = 0; rcpCount = 0; System.out.println("Table Nr." + (tCount++)); for (XWPFTableRow r : rList) { cList = r.getTableCells(); cCount = 0; rcpCount = 0; System.out.println("Row Nr." + (rCount++)); for (XWPFTableCell c : cList) { rcpList = c.getParagraphs(); rcpCount = 0; System.out.println("Cell Nr." + (cCount++)); System.out.println("Cell Text: " + c.getText()); System.out.println("Nr of Tables: " + c.getTables().size()); for (XWPFParagraph rcp : rcpList) { System.out.println("Par Nr." + (rcpCount++) + " Paragraphtext=" + rcp.getText()); } for (XWPFTable t1 : c.getTables()) { for (XWPFTableRow r1 : t1.getRows()) { for (XWPFTableCell c1 : r1.getTableCells()) { System.out.println("DC Nr." + dummCounter + " Cell Text: " + c1.getText()); switch (dummCounter) { case 0: wordReference.kundenLogo = c1.getText(); break; case 1: wordReference.kundenprofil = c1.getText(); break; case 2: wordReference.ausgangslage = c1.getText(); break; case 3: wordReference.losung = c1.getText(); break; case 4: wordReference.ergebnis = c1.getText(); break; case 5: wordReference.kunde = c1.getText(); break; case 6: wordReference.projektname = c1.getText(); break; case 7: wordReference.kundenstatement = c1.getText(); break; case 8: wordReference.statementBei = c1.getText(); break; case 9: wordReference.flisstext = c1.getText(); break; default: ; } dummCounter++; } } } } } } System.out.println(wordReference.toString(1)); } }
From source file:myexamples.WordDocsExamples.Test1.java
public static WordReference getWordReference() throws IOException { WordReference wordReference = new WordReference(); JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println(chooser.getSelectedFile().getName()); FileInputStream fis = new FileInputStream(chooser.getSelectedFile()); XWPFDocument doc = new XWPFDocument(fis); XWPFWordExtractor extract = new XWPFWordExtractor(doc); //System.out.println(extract.getText()); List<XWPFParagraph> pList = doc.getParagraphs(); List<XWPFTable> tList = doc.getTables(); // System.out.println("Number of Paragraphs="+pList.size()); // System.out.println("Number of Tables="+tList.size()); List<XWPFTableRow> rList; List<XWPFTableCell> cList; List<XWPFParagraph> rcpList; int tCount = 0, rCount = 0, cCount = 0, rcpCount = 0, dummCounter = 0; for (XWPFTable t : tList) { rList = t.getRows();// ww w . j a v a2s. c om rCount = 0; cCount = 0; rcpCount = 0; // System.out.println("Table Nr."+(tCount++)); for (XWPFTableRow r : rList) { cList = r.getTableCells(); cCount = 0; rcpCount = 0; // System.out.println("Row Nr."+(rCount++)); for (XWPFTableCell c : cList) { rcpList = c.getParagraphs(); rcpCount = 0; // System.out.println("Cell Nr."+(cCount++)); // System.out.println("Cell Text: "+c.getText()); // System.out.println("Nr of Tables: "+c.getTables().size()); for (XWPFParagraph rcp : rcpList) { // System.out.println("Par Nr."+(rcpCount++)+" Paragraphtext="+ rcp.getText()); } for (XWPFTable t1 : c.getTables()) { for (XWPFTableRow r1 : t1.getRows()) { for (XWPFTableCell c1 : r1.getTableCells()) { //System.out.println("DC Nr."+dummCounter+" Cell Text: "+c1.getText()); switch (dummCounter) { case 0: wordReference.kundenLogo = c1.getText(); break; case 1: wordReference.kundenprofil = c1.getText(); break; case 2: wordReference.ausgangslage = c1.getText(); break; case 3: wordReference.losung = c1.getText(); break; case 4: wordReference.ergebnis = c1.getText(); break; case 5: wordReference.kunde = c1.getText(); break; case 6: wordReference.projektname = c1.getText(); break; case 7: wordReference.kundenstatement = c1.getText(); break; case 8: wordReference.statementBei = c1.getText(); break; case 9: wordReference.flisstext = c1.getText(); break; default: ; } dummCounter++; } } } } } } //System.out.println(wordReference.toString(1)); } return wordReference; }
From source file:net.sourceforge.doddle_owl.data.Document.java
License:Open Source License
private String getTextString() { if (!file.exists()) { return ""; }/* ww w . j av a2 s. c om*/ try { FileInputStream fis = new FileInputStream(file); String fileName = file.getName().toLowerCase(); if (fileName.matches(".*.txt")) { return getTextString(new InputStreamReader(fis, "UTF-8")); } else if (fileName.matches(".*.pdf")) { PDFParser pdfParser = new PDFParser(fis); pdfParser.parse(); PDDocument pddoc = pdfParser.getPDDocument(); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(pddoc); pddoc.close(); return text; } else if (fileName.matches(".*.docx")) { XWPFDocument doc = new XWPFDocument(fis); return new XWPFWordExtractor(doc).getText(); } } catch (Exception ex) { ex.printStackTrace(); } return ""; }
From source file:nl.detoren.ijc.io.OutputIntekenlijst.java
License:Open Source License
public boolean export(Groepen groepen) { try {// w w w.j av a 2s . 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; } }