我有一个问题。我是对的,如果我有一个通过xssf
构造函数创建的工作簿,那么只需将构造函数更改为sxssf
工作簿(将xssf
wb作为参数传递)即可使其在stream mode
中工作?感谢lof的回答。
解决方案:这完全取决于您用于流式传输的类。如果您的类收集的流缓冲区超出了其容纳能力,则此操作将无效。否则会
最佳答案
你是对的。这两种实现之间的区别在于,流版本将数据直接写入流,并在内存中最多存储指定数量的行(默认值为100,并将其存储在SXSSFWorkbook.DEFAULT_WINDOW_SIZE中)。因此,写入输出流后将无法获得一些行数据。使用流实现的最大好处是减少了内存使用量。如果您需要导出大量数据,请使用SXSSFWorkbook。
例子:
public static void main(String[] args) throws IOException {
FileOutputStream inMemoryOut = new FileOutputStream(new File("inMemoryWorkbook.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook();
WorkbookExample example = new WorkbookExample(workbook, inMemoryOut);
example.export();
FileOutputStream streamOut = new FileOutputStream(new File("streamWorkbook.xlsx"));
SXSSFWorkbook streamWorkbook = new SXSSFWorkbook();
WorkbookExample streamExample = new WorkbookExample(streamWorkbook, streamOut);
streamExample.export();
}
public class WorkbookExample {
private Logger logger = Logger.getLogger(WorkbookExample.class.getName());
private Workbook workbook;
private OutputStream out;
public WorkbookExample(Workbook workbook, OutputStream out) {
this.workbook = workbook;
this.out = out;
}
public void export() throws IOException {
logger.info("export start for " + workbook.getClass().getName());
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 1000; i++) {
persons.add(new Person(String.valueOf("user_" + i)));
}
Sheet sheet = workbook.createSheet();
for (int i = 0; i < persons.size(); i++) {
Person p = persons.get(i);
Row row = sheet.createRow(i);
Cell cell = row.createCell(0);
cell.setCellValue(p.getName());
}
workbook.write(out);
logger.info("Is row 1 accessible after writing to output stream? " + String.valueOf(sheet.getRow(1) != null));
out.close();
workbook.close();
logger.info("export finished for " + workbook.getClass().getName());
}
public static class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
输出:
kwi 21, 2015 7:56:14 PM pepuch.html2pdf.WorkbookExample export
INFO: export start for org.apache.poi.xssf.usermodel.XSSFWorkbook
kwi 21, 2015 7:56:15 PM pepuch.html2pdf.WorkbookExample export
INFO: Is row 1 accessible after writing to output stream? true
kwi 21, 2015 7:56:15 PM pepuch.html2pdf.WorkbookExample export
INFO: export finished for org.apache.poi.xssf.usermodel.XSSFWorkbook
kwi 21, 2015 7:56:15 PM pepuch.html2pdf.WorkbookExample export
INFO: export start for org.apache.poi.xssf.streaming.SXSSFWorkbook
kwi 21, 2015 7:56:15 PM pepuch.html2pdf.WorkbookExample export
INFO: Is row 1 accessible after writing to output stream? false
kwi 21, 2015 7:56:15 PM pepuch.html2pdf.WorkbookExample export
INFO: export finished for org.apache.poi.xssf.streaming.SXSSFWorkbook
如您所见,使用SXSSFWorkbook写入输出流后,将无法再访问第1行。