Home > Mobile >  How to set change font colors by POI
How to set change font colors by POI

Time:01-13

I use below code to update MS Word by using POI in my selenium scripts.

public class WordAutomation {

    public static String projectpath = System.getProperty("user.dir");
    public static FileOutputStream out;
    public static String ScreenshotPath = projectpath "\\Screenshots\\";
    public static XWPFDocument docx;
    public static XWPFRun run;
    public static String wordFile;


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

        docx = new XWPFDocument();
        run = docx.createParagraph().createRun();
        wordFile = ScreenshotPath "ScreenshotFile.docx";
        out = new FileOutputStream(wordFile);
    
        run.setText("Test Started");
        run.addBreak();
        run.setText("Its a Pass scenario");
        run.addBreak();
        run.setColor("ff0000");//Change the font color to red
        run.setText("Its a Fail scenario");
        run.addBreak();
        run.setColor("000000");//back to black again
        run.setText("Its a Pass scenario");
        docx.write(out);
        out.flush();
        out.close();
        docx.close();
    }
}

I need output like below

enter image description here

but i am getting output like below

enter image description here

Please help me to solve my issue. Actually i want to save the document to implement the changes and continue further.

CodePudding user response:

It looks like a new run has to be created for each change in style; see link below. This works:

    docx = new XWPFDocument();
    wordFile = screenshotPath "ScreenshotFile.docx";
    out = new FileOutputStream(wordFile);

    p = docx.createParagraph();

    run = p.createRun();
    run.setText("Test Started");
    run.addBreak();

    run = p.createRun();
    run.setText("Its a Pass scenario");
    run.addBreak();

    run = p.createRun();
    run.setColor("FF0000");
    run.setText("Its a Fail scenario");
    run.addBreak();

    run = p.createRun();
    run.setText("Its a Pass scenario");
    run.addBreak();

    docx.write(out);
    out.flush();
    out.close();
    docx.close();

See also: https://stackoverflow.com/a/41681461/127971

  • Related