Example usage for org.apache.poi.xwpf.usermodel XWPFRun setText

List of usage examples for org.apache.poi.xwpf.usermodel XWPFRun setText

Introduction

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

Prototype

public void setText(String value, int pos) 

Source Link

Document

Sets the text of this text run in the

Usage

From source file:easyoffice.word.WordMaker.java

private static void replaceText(XWPFDocument doc, HashMap<String, String> data) {

    Set<String> keySet = data.keySet();

    for (String key : keySet) {
        for (XWPFParagraph p : doc.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();

            for (XWPFRun run : runs) {
                if (run.toString().toLowerCase().equals(key)) {
                    run.setText(data.get(key), 0);
                }/*from  w w  w . j  a  va 2  s  .  c o m*/
            }
        }
    }
}

From source file:javaapplication1.AnotherPOI.java

public static void replaceText(String findText, String replaceText) {
    try {// w w w  .  j a  v  a2s .co  m
        XWPFDocument doc = new XWPFDocument(OPCPackage.open("D:\\template.docx"));
        for (XWPFParagraph p : doc.getParagraphs()) {

            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(findText)) {
                        text = text.replace(findText, replaceText);
                        r.setText(text, 0);
                    }
                }
            }
        }
        for (XWPFTable tbl : doc.getTables()) {
            for (XWPFTableRow row : tbl.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String text = r.getText(0);
                            if (text.contains(findText)) {
                                text = text.replace(findText, replaceText);
                                r.setText(text);
                            }
                        }
                    }
                }
            }
        }
        doc.write(new FileOutputStream("D:\\result.docx"));
    } catch (IOException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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);
                System.out.println(text);
            }/*from   w w w . ja  v a  2s.c  o m*/

            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:offishell.word.Word.java

License:MIT License

/**
 * <p>//w  ww  .  j a  v  a  2  s . co m
 * Add new paragraph.
 * </p>
 * 
 * @param text A paragraph text.
 * @return
 */
public Word text(String text) {
    XWPFParagraph para = createParagraph();
    XWPFRun run = para.createRun();
    run.setText(text, 0);
    styles().base().apply(run);

    return this;
}

From source file:offishell.word.WordHeleper.java

License:MIT License

/**
 * <p>/*from   www .j  av a 2  s  .c om*/
 * Helper method to remove all text from the specified paragraph.
 * </p>
 * 
 * @param paragraph A target paragraph.
 */
public static void clearText(XWPFParagraph paragraph) {
    if (paragraph != null) {
        for (XWPFRun run : paragraph.getRuns()) {
            run.setText("", 0);
        }
    }
}

From source file:offishell.word.WordHeleper.java

License:MIT License

/**
 * <p>//from  www.  j a va  2  s  .  c  o m
 * Write the text.
 * </p>
 * 
 * @param run
 * @param text
 */
public static void write(XWPFRun run, String text) {
    String[] lines = text.split("\n");

    if (lines.length != 0) {
        run.setText(lines[0], 0); // set first line into XWPFRun

        for (int i = 1; i < lines.length; i++) {
            run.addBreak();
            run.setText(lines[i]);
        }
    }
}

From source file:org.cgiar.ccafs.marlo.utils.POISummary.java

License:Open Source License

private void addParagraphTextBreak(XWPFRun paragraphRun, String text) {
    if (text.contains("\n")) {
        String[] lines = text.split("\n");
        paragraphRun.setText(lines[0], 0); // set first line into XWPFRun
        for (int i = 1; i < lines.length; i++) {
            // add break and insert new text
            paragraphRun.addBreak();// w  ww . ja  va2s  .com
            paragraphRun.setText(lines[i]);
        }
    } else {
        paragraphRun.setText(text, 0);
    }
}

From source file:org.eclipse.sw360.licenseinfo.outputGenerators.DocxUtils.java

License:Open Source License

private static void replaceParagraph(XWPFParagraph paragraph, String placeHolder, String replaceText) {
    for (XWPFRun run : paragraph.getRuns()) {
        String text = run.getText(run.getTextPosition());
        if (text != null && text.contains(placeHolder)) {
            text = text.replace(placeHolder, replaceText);
            String[] split = text.split("\n");
            run.setText(split[0], 0);
            for (int i = 1; i < split.length; i++) {
                run.addBreak();//  w  w w  .  j  a va2 s . c o m
                run.setText(split[i]);
            }
        }
    }
}

From source file:org.kino.server.api.contractgenerator.java

static private long replaceInParagraphs(Map<String, String> replacements, List<XWPFParagraph> xwpfParagraphs) {
    long count = 0;
    for (XWPFParagraph paragraph : xwpfParagraphs) {
        List<XWPFRun> runs = paragraph.getRuns();

        for (Map.Entry<String, String> replPair : replacements.entrySet()) {
            String find = replPair.getKey();
            String repl = replPair.getValue();
            TextSegement found = paragraph.searchText(find, new PositionInParagraph());
            if (found != null) {
                count++;/* ww  w .  j  av  a 2 s .co  m*/
                if (found.getBeginRun() == found.getEndRun()) {
                    // whole search string is in one Run
                    XWPFRun run = runs.get(found.getBeginRun());
                    String runText = run.getText(run.getTextPosition());
                    String replaced = runText.replace(find, repl);
                    run.setText(replaced, 0);
                } else {
                    // The search string spans over more than one Run
                    // Put the Strings together
                    StringBuilder b = new StringBuilder();
                    for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
                        XWPFRun run = runs.get(runPos);
                        b.append(run.getText(run.getTextPosition()));
                    }
                    String connectedRuns = b.toString();
                    String replaced = connectedRuns.replace(find, repl);

                    // The first Run receives the replaced String of all connected Runs
                    XWPFRun partOne = runs.get(found.getBeginRun());
                    partOne.setText(replaced, 0);
                    // Removing the text in the other Runs.
                    for (int runPos = found.getBeginRun() + 1; runPos <= found.getEndRun(); runPos++) {
                        XWPFRun partNext = runs.get(runPos);
                        partNext.setText("", 0);
                    }
                }
            }
        }
    }
    return count;
}

From source file:service.GenerationLettres.CreerPiecesManquantes.java

/**
* 
* @param filename - Nom du fichier modle de demande des pices manquantes.
* @param idDossier - Identifiant du dossier pour lequel l est cr
* @throws InvalidFormatException/*from  w w w  . jav  a 2s.c  o  m*/
* @throws IOException 
*/
public void replacePiecesManquantes(String filename, Formation formation, String sexe, String nom,
        String prenom, String adresse, Adresse adresseEntite, List<Justificatif> justificatifsOk)
        throws InvalidFormatException, IOException {
    List<Justificatif> lesJustificatifs = formation.getLesJustificatifs();

    Date dateActuelle = new Date();
    DateFormat dateForm = new SimpleDateFormat("dd MMMM yyyy", Locale.FRANCE);
    String date = dateForm.format(dateActuelle);
    String codePostal = adresseEntite.getCodePostal();
    String ville = adresseEntite.getVille();
    String civilite = "";
    if (sexe.equals("Masculin"))
        civilite = "Monsieur";
    if (sexe.equals("Feminin"))
        civilite = "Madame";

    String intitule = formation.getIntitule();

    if (justificatifsOk != null) {
        for (Justificatif just : justificatifsOk) {
            lesJustificatifs.remove(just);
        }
    }

    String newFileName = nom + prenom + " Lettre piecesManquantes.docx";

    File file = new File(PATH_MODELS + "/" + filename);
    FileInputStream fis = new FileInputStream(file.getAbsolutePath());
    XWPFDocument doc = new XWPFDocument(fis);
    doc.write(new FileOutputStream(PATH_TARGET + "/" + newFileName));
    doc.close();

    doc = new XWPFDocument(OPCPackage.open(PATH_TARGET + "/" + newFileName));

    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$formation")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$formation", intitule);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la formation effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$date")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$date", date);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la date effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$civilite")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$civilite", civilite);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la civilite effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$prenom")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$prenom", prenom);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement du prenom effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$nom")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$nom", nom);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement du nom effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$adresse")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$adresse", adresse);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de l'adresse effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$codePostal")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$codePostal", codePostal);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement du code postal effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$ville")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$ville", ville);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la ville effectue");
        }
    }

    XWPFTable table = doc.createTable(lesJustificatifs.size(), 2);
    table.setCellMargins(200, 250, 0, 250);
    int i = 0;
    for (XWPFTableRow r : table.getRows()) {
        XWPFTableCell cell = r.getCell(0);
        cell.setText(lesJustificatifs.get(i).getTitre());
        cell = r.getCell(1);
        cell.setText(lesJustificatifs.get(i).getDescription());
        i++;
    }

    doc.write(new FileOutputStream(PATH_TARGET + "/temp.docx"));
    new File(PATH_TARGET + "/temp.docx").delete();
    doc.close();
    //copyTempToFile(filename);
    System.out.println("replaceLettrePiecesManquantes DONE");
}