记一次用POI写Excel遇到的异常
报的异常如下
java.io.IOException: Cannot write data, document seems to have been closed already
at org.apache.poi.ooxml.POIXMLDocument.write(POIXMLDocument.java:230)
at util.XlsxWriteUtile.numStreamByValue(XlsxWriteUtile.java:39)
at importData.SQLServerDB.RunBCPInData(SQLServerDB.java:242)
at importData.SQLServerDB.copyFromFile(SQLServerDB.java:110)
at importData.importData.exec(importData.java:168)
原因是因为POIXMLDocument 里的 OPCPackage pkg是null了
public abstract class POIXMLDocument extends POIXMLDocumentPart implements Closeable {
@SuppressWarnings("resource")
public final void write(OutputStream stream) throws IOException {
OPCPackage p = getPackage();
if(p == null) {
throw new IOException("Cannot write data, document seems to have been closed already");
}
//force all children to commit their changes into the underlying OOXML Package
// TODO Shouldn't they be committing to the new one instead?
Set<PackagePart> context = new HashSet<>();
onSave(context);
context.clear();
//save extended and custom properties
getProperties().commit();
p.save(stream);
}
}
为啥,因为在某个地方调用过了close()了.造成第二次写的时候OPCPackage是null,跟OutputStream没有关系.
public abstract class POIXMLDocument extends POIXMLDocumentPart implements Closeable {
...
@Override
public void close() throws IOException {
if (pkg != null) {
if (pkg.getPackageAccess() == PackageAccess.READ) {
pkg.revert();
} else {
pkg.close();
}
pkg = null;
}
}
所以,调整自己的程序结构吧