Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a XWPFDocument from a byte[]?

Tags:

java

xwpf

I have a Microsoft Word .docx document uploaded to Sharepoint. In my java code, I have downloaded this document into a byte[]. Ok. Now, what I want is to process this byte[] to obtain an XWPFDocument and be able to replace some variables into the document.

Please, could anybody help me?

Thanks!!

like image 619
user3270931 Avatar asked Aug 30 '25 18:08

user3270931


1 Answers

You can read as XWPFDocument from byte[] by using InputStream(ByteArrayInputStream) specified in the constructor of XWPFDocument and you can get paragraphs and runs from XWPFDocument. After that you can edit like below.

byte[] byteData = ....

// read as XWPFDocument from byte[]
XWPFDocument doc = new XWPFDocument(new ByteArrayInputStream(byteData));

int numberToPrint = 0;

// you can edit paragraphs
for (XWPFParagraph para : doc.getParagraphs()) {
    List<XWPFRun> runs = para.getRuns();

    numberToPrint++;

    for (XWPFRun run : runs) {

        // read text
        String text = run.getText(0);

        // edit text and update it
        run.setText(numberToPrint + " " + text, 0);
    }
}

// save it and you can get the updated .docx
FileOutputStream fos = new FileOutputStream(new File("updated.docx"));
doc.write(fos);
like image 137
riversun Avatar answered Sep 02 '25 07:09

riversun