Example usage for org.apache.poi.xwpf.usermodel XWPFDocument write

List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument write

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFDocument write.

Prototype

@SuppressWarnings("resource")
public final void write(OutputStream stream) throws IOException 

Source Link

Document

Write out this document to an Outputstream.

Usage

From source file:Management.Projects.java

public String CrearMinuta(String datos[], int idProject, String[] Asistentes, String[] puntos)
        throws IOException {
    String result = "";
    ArrayList<XWPFParagraph> listfecha = new ArrayList<>();
    ArrayList<XWPFParagraph> listasistentes = new ArrayList<>();
    ArrayList<XWPFParagraph> listpuntos = new ArrayList<>();
    XWPFDocument doc = new XWPFDocument();
    int i;//from w  ww  .  j a  va 2 s.  c  om
    XWPFParagraph p3;
    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setBorderBottom(Borders.DOUBLE);
    p1.setBorderTop(Borders.DOUBLE);
    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("Datos de la minuta");
    r1.setBold(true);
    for (i = 0; i < datos.length; i++) {
        p3 = doc.createParagraph();
        listfecha.add(p3);

    }
    i = 0;
    for (XWPFParagraph para : listfecha) {
        XWPFRun r2 = para.createRun();
        r2.setText(datos[i]);
        r2.setFontSize(20);
        i++;
    }

    XWPFParagraph parrafoAsistentes = doc.createParagraph();
    parrafoAsistentes.setAlignment(ParagraphAlignment.CENTER);
    parrafoAsistentes.setBorderBottom(Borders.DOUBLE);
    parrafoAsistentes.setBorderTop(Borders.DOUBLE);
    XWPFRun r2 = parrafoAsistentes.createRun();
    r2.setBold(true);
    r2.setText("Asistentes:");
    r2.setBold(true);

    XWPFParagraph p4;
    for (i = 0; i < Asistentes.length; i++) {
        p4 = doc.createParagraph();
        listasistentes.add(p4);

    }

    i = 0;
    for (XWPFParagraph para : listasistentes) {
        XWPFRun r3 = para.createRun();
        r3.setText(Asistentes[i]);
        r3.setFontSize(20);
        i++;
    }

    XWPFParagraph parrafoPuntos = doc.createParagraph();
    parrafoPuntos.setAlignment(ParagraphAlignment.CENTER);
    parrafoPuntos.setBorderBottom(Borders.DOUBLE);
    parrafoPuntos.setBorderTop(Borders.DOUBLE);
    XWPFRun r3 = parrafoPuntos.createRun();
    r3.setBold(true);
    r3.setText("Puntos a Tratar:");
    r3.setBold(true);

    XWPFParagraph p5;
    for (i = 0; i < puntos.length; i++) {
        p5 = doc.createParagraph();
        listpuntos.add(p5);

    }
    i = 0;
    for (XWPFParagraph para : listpuntos) {
        XWPFRun r4 = para.createRun();
        r4.setText(puntos[i]);
        r4.setFontSize(20);
        i++;
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(System.getProperty("user.home")
                + "/Documents/NetBeansProjects/StickMaps/web/Minutas/Minuta" + idProject + ".docx");
    } catch (FileNotFoundException ex) {
        System.out.println(ex.toString());
        return ex.toString();
    }
    doc.write(out);
    result = "bien";
    out.close();

    return result;
}

From source file:Management.PruebaDoc.java

public static void main(String[] args) throws IOException {

    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p3 = doc.createParagraph();
    XWPFRun r4 = p3.createRun();//w w w  .jav  a 2  s.  com
    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);

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(
                "C:\\Users\\hilsierivan\\Documents\\NetBeansProjects\\StickMaps\\web\\MapImages\\simple.docx");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(PruebaDoc.class.getName()).log(Level.SEVERE, null, ex);
    }
    doc.write(out);
    out.close();

}

From source file:modificarcabeceradocs.appModificacionDOCs.java

private void modificarDOCs(File pathsDocumento) throws FileNotFoundException, IOException {
    XWPFDocument doc = new XWPFDocument();

    XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
    if (policy.getDefaultHeader() == null && policy.getFirstPageHeader() == null
            && policy.getDefaultFooter() == null) {
        // Need to create some new headers
        // The easy way, gives a single empty paragraph
        XWPFHeader headerD = policy.createHeader(policy.DEFAULT);
        //headerD.getParagraphs().createRun().setText("Hello Header World!");
        headerD.getParagraphArray(0).createRun().setText("AAAAAAAAAAAAA");

        // Or the full control way
        CTP ctP1 = CTP.Factory.newInstance();
        CTR ctR1 = ctP1.addNewR();//  w  ww.j  a v a2 s  .  c  o  m
        CTText t = ctR1.addNewT();
        t.setStringValue("Paragraph in header");

        XWPFParagraph p1 = new XWPFParagraph(ctP1, doc);
        XWPFParagraph[] pars = new XWPFParagraph[1];
        pars[0] = p1;

        policy.createHeader(policy.FIRST, pars);

        doc.write(new FileOutputStream(new File("prueba.docx")));
        System.out.println("Cabecera terminada");
    } else {
        // Already has a header, change it
    }
}

From source file:msoffice.ReadWord.java

public static void main(String[] args) {

    try {//from   www. j  a v  a 2 s .  com
        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);//from   w ww.  ja va 2s .c om
                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:nl.architolk.ldt.processors.WordSerializer.java

License:Open Source License

protected void readInput(final PipelineContext pipelineContext, final ProcessorInput input, Config config,
        OutputStream outputStream) {

    try {//  w w  w  .j ava2s  .c  o  m
        // Test
        BigInteger markId = BigInteger.ONE;
        // Read the input as a DOM
        final Document domDocument = readInputAsDOM(pipelineContext, input);

        // create document (docx)
        XWPFDocument doc = new XWPFDocument();

        //iterate through paragraphs;
        NodeList paragraphNodes = domDocument.getElementsByTagName("p");

        for (short i = 0; i < paragraphNodes.getLength(); i++) {
            Node paragraphNode = paragraphNodes.item(i);
            if (paragraphNode.getNodeType() == Node.ELEMENT_NODE) {
                //Create new paragraph
                XWPFParagraph paragraph = doc.createParagraph();

                //iterate through paragraph parts
                NodeList textNodes = paragraphNode.getChildNodes();
                for (short r = 0; r < textNodes.getLength(); r++) {
                    Node textNode = textNodes.item(r);
                    if (textNode.getNodeType() == Node.TEXT_NODE) {
                        XWPFRun run = paragraph.createRun();
                        run.setText(textNode.getTextContent());
                    }
                    if (textNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element textElement = (Element) textNode;
                        if (textNode.getLocalName().toUpperCase().equals("B")) {
                            //Eigenlijk op een andere plaats, maar nu ff voor de test
                            String anchor = textElement.getAttribute("id");
                            if (!anchor.isEmpty()) {
                                CTBookmark bookStart = paragraph.getCTP().addNewBookmarkStart();
                                bookStart.setName(anchor);
                                bookStart.setId(markId);
                            }
                            XWPFRun run = paragraph.createRun();
                            run.setBold(true);
                            run.setText(textNode.getTextContent());
                            if (!anchor.isEmpty()) {
                                CTMarkupRange bookEnd = paragraph.getCTP().addNewBookmarkEnd();
                                bookEnd.setId(markId);
                                markId = markId.add(BigInteger.ONE);
                            }
                        } else if (textNode.getLocalName().toUpperCase().equals("A")) {
                            addHyperlink(paragraph, textNode.getTextContent(),
                                    textElement.getAttribute("href"));
                        } else {
                            XWPFRun run = paragraph.createRun();
                            run.setText(textNode.getTextContent());
                        }
                    }
                }
            }
        }
        // write workbook to stream
        doc.write(outputStream);
        outputStream.close();

    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:nl.detoren.ijc.io.OutputIntekenlijst.java

License:Open Source License

public boolean export(Groepen groepen) {
    try {/*ww w .  java 2s .c o 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;
    }
}

From source file:oop.nhom5.de3.model.IOFileWord.java

public static boolean writeWord(String text, String fileName) {
    //Blank Document
    XWPFDocument document = new XWPFDocument();
    //Write the Document in file system
    try {/*w ww .  j  av a 2s .  c o m*/
        FileOutputStream out = new FileOutputStream(new File(fileName));
        String[] lines = text.split("\n");
        //create Paragraph
        for (String line : lines) {
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText(line);
        }

        document.write(out);
        out.close();
        return true;
    } catch (IOException | HeadlessException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.articleEditor.articleKit.DocxEditorKit.java

License:Apache License

/**
 * Write content from a document to the given stream in a format appropriate for this kind of content handler.
 *
 * @param out The stream to write to//from   w ww. j a va 2s  .  c  o  m
 * @param doc The source for the write.
 * @param pos The location in the document to fetch the content.
 * @param len The amount to write out.
 * @exception IOException on any I/O error
 * @exception BadLocationException if pos represents an invalid location within the document.
 */
@Override
public void write(OutputStream out, Document doc, int pos, int len) throws IOException, BadLocationException {
    XWPFDocument poiDocument = (XWPFDocument) doc.getProperty("XWPFDocument");
    poiDocument.write(out);
}

From source file:org.articleEditor.articleKit.DocxEditorKit.java

License:Apache License

/**
 * Write content from a document to the given file as plain text.
 *
 * @param   fileName ?out? The name of source file to write to
 * @param   doc The source for the write.
 * @exception   IOException on any I/O error
 * @exception   BadLocationException if pos represents an invalid location within the document.
 *//*from  w  ww . j  a v a 2s  .  c o  m*/
public void write(String fileName, Document doc) throws IOException, BadLocationException {
    XWPFDocument poiDocument = (XWPFDocument) doc.getProperty("XWPFDocument");
    try (FileOutputStream out = new FileOutputStream(fileName)) {
        poiDocument.write(out);
    }
}