web-dev-qa-db-fra.com

Comment créer un simple fichier docx avec Apache POI?

Je recherche un exemple de code simple ou un tutoriel complet sur la création d'un fichier docx avec Apache POI et son openxml4j.

J'ai essayé le code suivant (avec beaucoup d'aide de Content Assist, merci Eclipse!) Mais le code ne fonctionne pas correctement.

String tmpPathname = aFilename + ".docx";
File tmpFile = new File(tmpPathname);

ZipPackage tmpPackage = (ZipPackage) OPCPackage.create(tmpPathname);
PackagePartName tmpFirstPartName = PackagingURIHelper.createPartName("/FirstPart");
PackagePart tmpFirstPart = tmpPackage.createPart(tmpFirstPartName, "ISO-8859-1");

XWPFDocument tmpDocument = new XWPFDocument(tmpPackage); //Exception
XWPFParagraph tmpParagraph = tmpDocument.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText("LALALALAALALAAAA");
tmpRun.setFontSize(18);
tmpPackage.save(tmpFile);

L'exception levée est la suivante:

Exception in thread "main" Java.lang.NullPointerException
    at org.Apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.Java:235)
    at org.Apache.poi.POIXMLDocument.load(POIXMLDocument.Java:196)
    at org.Apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.Java:94)
    at DocGenerator.makeDocxWithPoi(DocGenerator.Java:64)
    at DocGenerator.main(DocGenerator.Java:50)

Quelqu'un peut-il m'aider avec mes exigences (vraiment simples)?

34
guerda

Voici comment créer un simple fichier docx avec POI:

XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText("LALALALAALALAAAA");
tmpRun.setFontSize(18);
document.write(new FileOutputStream(new File("yourpathhere")));
document.close();
41
Valentin Rocher
import Java.io.File;   
  import Java.io.FileOutputStream;   
  import org.Apache.poi.xwpf.usermodel.XWPFDocument;   
  import org.Apache.poi.xwpf.usermodel.XWPFParagraph;   
  import org.Apache.poi.xwpf.usermodel.XWPFRun;   
  public class DocFile {   
    public void newWordDoc(String filename, String fileContent)   
         throws Exception {   
       XWPFDocument document = new XWPFDocument();   
       XWPFParagraph tmpParagraph = document.createParagraph();   
       XWPFRun tmpRun = tmpParagraph.createRun();   
       tmpRun.setText(fileContent);   
       tmpRun.setFontSize(18);   
       FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\amitabh\\Pictures\\pics\\"+filename + ".doc"));   
       document.write(fos);   
       fos.close();   
    }   
    public static void main(String[] args) throws Exception {   
         DocFile app = new DocFile();   
         app.newWordDoc("testfile", "Hi hw r u?");   

    }   
  }   
1
Amitabh Ranjan