Generare documenti Word da Java è comune per report, contratti, lettere automatiche. La libreria standard de facto è Apache POI (specificamente POI-OOXML per `.docx` OOXML). Non usa `RtfWriter2` (vecchio, per RTF, non più mantenuto). Ecco come fare con API moderne.
Dipendenze (Maven / Gradle)
org.apache.poi poi-ooxml 5.3.0
// Gradle: build.gradle implementation 'org.apache.poi:poi-ooxml:5.3.0'
Codice base: Crea documento semplice
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreaWord {
public static void main(String[] args) {
// 1. Crea documento vuoto
XWPFDocument doc = new XWPFDocument();
// 2. Crea paragrafo con testo
XWPFParagraph para = doc.createParagraph();
XWPFRun run = para.createRun();
run.setText("Solo un altro paragrafo di testo");
run.setBold(true);
run.setFontSize(12);
run.setFontFamily("Calibri");
// 3. Aggiungi altro paragrafo (titolo)
XWPFParagraph title = doc.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setText("Report Mensile Vendite");
titleRun.setBold(true);
titleRun.setFontSize(18);
titleRun.setColor("2F5496"); // RGB esadecimale
// 4. Tabella semplice
XWPFTable table = doc.createTable(3, 3); // 3 righe, 3 colonne
String[][] dati = {
{"Mese", "Vendite", "Target"},
{"Gennaio", "1250", "1000"},
{"Febbraio", "1320", "1100"}
};
for (int r = 0; r < 3; r++) {
XWPFTableRow row = table.getRow(r);
for (int c = 0; c < 3; c++) {
row.getCell(c).setText(dati[r][c]);
}
}
// 5. Salva su file
try (FileOutputStream out = new FileOutputStream("report_vendite.docx")) {
doc.write(out);
System.out.println("Documento creato: report_vendite.docx");
} catch (IOException e) {
e.printStackTrace();
} finally {
try { doc.close(); } catch (IOException ignored) {}
}
}
}
Operazioni comuni
Stili e formattazione
// Stile titolo predefinito
XWPFParagraph p = doc.createParagraph();
p.setStyle("Heading1"); // Heading1, Heading2, ... (stili Word nativi)
XWPFRun r = p.createRun();
r.setText("Capitolo 1: Introduzione");
// Elenco puntato
XWPFParagraph bullet = doc.createParagraph();
bullet.setStyle("ListBullet");
bullet.createRun().setText("Primo punto");
// Interruzione pagina
XWPFParagraph bp = doc.createParagraph();
bp.createRun().addBreak(BreakType.PAGE);
Immagini
import java.io.FileInputStream;
// ...
XWPFParagraph imgPara = doc.createParagraph();
imgPara.setAlignment(ParagraphAlignment.CENTER);
XWPFRun imgRun = imgPara.createRun();
try (FileInputStream is = new FileInputStream("logo.png")) {
imgRun.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, "logo.png", Units.toEMU(400), Units.toEMU(200)); // larghezza, altezza in EMU (1 pt = 12700 EMU)
} catch (IOException e) { e.printStackTrace(); }
Intestazione / Piè di pagina
XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
XWPFParagraph hp = header.createParagraph();
hp.setAlignment(ParagraphAlignment.RIGHT);
hp.createRun().setText("Riservato - " + java.time.LocalDate.now());
XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);
XWPFParagraph fp = footer.createParagraph();
fp.setAlignment(ParagraphAlignment.CENTER);
XWPFRun fRun = fp.createRun();
fRun.setText("Pagina ");
// Numero pagina richiede campo Word complesso (CTFldChar), vedi POI docs
Proprietà documento (metadati)
doc.getProperties().getCoreProperties().setTitle("Report Vendite Q1 2024");
doc.getProperties().getCoreProperties().setCreator("Sistema Automatico");
doc.getProperties().getCoreProperties().setSubject("Vendite Mensili");
doc.getProperties().getCoreProperties().setCreated(java.time.LocalDateTime.now());
Best practices
- Chiudi sempre `doc.close()` in blocco `finally` o `try-with-resources` (rilascia risorse, file handle)
- Usa try-with-resources per `FileOutputStream`
- Per documenti grandi (100+ pagine, tante immagini): POI consuma molta RAM. Considera SXWPFDocument (streaming, low memory) o genera in chunk.
- Testa su LibreOffice e Word: rendering può differire
- Per template complessi: usa docx4j (JAXB-based, più potente per binding XML/template) o Apache POI + template .docx (apri template, sostituisci placeholder, salva)
Alternative a POI
| Libreria | Pro | Contro |
|---|---|---|
| docx4j | JAXB, manipolazione XML diretta, potente per template, binding dati | Curva apprendimento ripida, più verboso |
| Aspose.Words for Java | Completo, fedeltà Word massima, report engine (LINQ Reporting), supporto pro | Commerciale (licenza costosa) |
| JODConverter / LibreOffice headless | Converte qualsiasi formato via LibreOffice (HTML, MD, LaTeX → DOCX/PDF) | Richiede LibreOffice installato, processo esterno, più lento |
| OpenHTMLToPDF / Flying Saucer | HTML/CSS → PDF (non DOCX) | Non genera .docx |