This issue is not really specific to POI. The problem is that streams
provide mostly sequential access to data. The code as you have
written just writes two complete workbooks to the same stream (Excel
probably silently ignores the second one).
Theoretically, POI could have been written to provide non-stream based
output (i.e. only 'dirty' parts of the workbook would be written out
when requested), but this would be very complicated to implement. I
would hazard a guess that even Excel uses plain stream based output.
Below is some code that I hope is useful.
----
// For clarity, the following code will work (but seems to be what you
wanted to avoid):
File file = new File("/tmp/Test.xls");
OutputStream os;
cell.setCellValue(1.5);
os = new FileOutputStream(file);
workbook.write(os);
os.close();
cell.setCellValue(3.5);
os = new FileOutputStream(file); // re-open stream here
workbook.write(os);
os.close();
---------
// Alternatively, if you are really keen on holding onto a single file
handle, you could try something like this:
File file = new File("/tmp/Test.xls");
ResettableOutputSteam os = new ResettableOutputSteam(file);
cell.setCellValue(1.5);
os.reset();
workbook.write(os);
os.close();
cell.setCellValue(3.5);
os.reset();
workbook.write(os);
os.close();
// ResettableOutputStream wraps a RandomAccessFile and extends OutputStream.
// Here is a rough draft of something that should work
public final class ResettableOutputStream extends OutputStream {
private final RandomAccessFile _raf;
public ResettableOutputStream(File f) throws FileNotFoundException {
_raf = new RandomAccessFile(f, "rw");
}
public void write(int b) throws IOException {
_raf.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
_raf.write(b, off, len);
}
public void close() throws IOException {
_raf.setLength(_raf.getFilePointer());
}
public void reset() throws IOException {
_raf.seek(0);
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]