首先,我需要在我的程序中创建一个文件,如下所示:
File file = new File(jChooser.getSelectedFile().getPath()+".docx");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
然后,我需要向其中添加一些信息,如下所示:
OPCPackage pack = POIXMLDocument.openPackage(path); //this path is the file's path;
XWPFDocument doc = new XWPFDocument(pack);
XWPFParagraph paragraph = doc.createParagraph();
paragraph.setAlignment(wordFont.getAlign());
XWPFRun run = paragraph.insertNewRun(paragraph.getRuns().size());
run.setText(data);
当我运行它时,它有这样的错误:
Exception in thread "AWT-EventQueue-0"org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: 'C:\Users\sks\Desktop\17.docx'
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:103)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:207)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:186)
at org.apache.poi.POIXMLDocument.openPackage(POIXMLDocument.java:67)
我该如何解决这个问题?
我已经解决了这个问题,创建时只需使用XWPFDocument:
XWPFDocument xwpfDocument = new XWPFDocument();
File file = new File("hello.docx");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
xwpfDocument.write(new FileOutputStream(file));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}