Cannot write data, document seems to have been closed already

记一次用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;
        }
    }

所以,调整自己的程序结构吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值