获取SXSSFWorkbook的文件大小

时间:2017-07-03 18:56:30

标签: java apache-poi

有没有办法获得SXSSFWorkbook生成的Excel大小。

我需要检查生成的文件的大小,并根据大小执行不同的操作,例如,如果大小较小,则直接发送电子邮件,如果大小超过某个限制,则上传到某个位置。

由于

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案:您可以将Workbook写入文件,然后分析其大小。

Workbook wb = ...
try (OutputStream os = new FileOutputStream("sheet.xlsx")) {
    wb.write(os);
}
long len = new File("sheet.xlsx").length();
if (len > 1024_1024) {
    // upload
} else {
    // email
}

如果要限制文件大小,如果超出此限制就失败,可以使用以下包装器包装OutputStream

public class LimitingOutputStream extends OutputStream {
    private final OutputStream stream;
    private final long limitInBytes;
    private final AtomicLong bytesWritten = new AtomicLong();

    public LimitingOutputStream(@NotNull OutputStream out, long limitInBytes) {
        stream = out;
        this.limitInBytes = limitInBytes;
    }

    @Override
    public void write(int b) throws IOException {
        increaseCounterAndValidateNotOverflown(1);
        stream.write(b);
    }

    @Override
    public void write(@NotNull byte[] b) throws IOException {
        increaseCounterAndValidateNotOverflown(b.length);
        stream.write(b);
    }

    @Override
    public void write(@NotNull byte[] b, int off, int len) throws IOException {
        increaseCounterAndValidateNotOverflown(len);
        stream.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        stream.flush();
    }

    @Override
    public void close() throws IOException {
        stream.close();
    }

    private void increaseCounterAndValidateNotOverflown(int delta) throws IOException {
        long count = bytesWritten.addAndGet(delta);
        if (count > limitInBytes) {
            throw new IOException(String.format("Output stream overflown; only %d allowed, but tried to write %d bytes", limitInBytes, count));
        }
    }
}

一样使用它
try (OutputStream os = new LimitingOutputStream(new FileOutputStream("sheet.xlsx"), 1024_1024)) {