Apache POI es una librería Java que nos permite crear, leer, modificar, ... documentos de Microsoft Office.
A la hora de generar un documento docx, podemos crearnos un documento plantilla con diferentes variables (por ejemplo, ${miVariable}), leerlo con Apache POI, reemplazar estas variables y generar el nuevo documento. Esto lo podemos hacer de la siguiente manera:
A la hora de generar un documento docx, podemos crearnos un documento plantilla con diferentes variables (por ejemplo, ${miVariable}), leerlo con Apache POI, reemplazar estas variables y generar el nuevo documento. Esto lo podemos hacer de la siguiente manera:
try (XWPFDocument template = new XWPFDocument(new FileInputStream(myFilePath))) { for (XWPFParagraph paragraph: template.getParagraphs()){ for (XWPFRun run : paragraph.getRuns()) { if (run.text().contains("${myVariable}")) { run.setText(run.text().replace("${myVariable}", "myValue"), 0); } } } template.write(new FileOutputStream(new File(myOutputFilePath))); }Otra manera sería coger todo el texto xml que representa a nuestra plantilla y reemplazar las variables.
try (XWPFDocument template = new XWPFDocument(new FileInputStream(myFile))) { CTBody body = template.getDocument().getBody(); String templateContent = body.xmlText(); templateContent = templateContent.replace("myVariable", "myValue"); body.set(CTBody.Factory.parse(templateContent)); template.write(new FileOutputStream(new File(outputFile))); }Yo he utilizado Maven, y para este ejemplo he tenido que incluir las siguientes dependencias:
org.apache.poi poi 3.15 org.apache.poi poi-ooxml 3.15