通过servlet的jXML流结果,而不保存到磁盘

时间:2014-07-29 10:57:34

标签: java excel servlets jxls

我使用jXLS从模板创建报告:

List report = new ArrayList();
report.add(new ReportItem(12,"item name 1"));
report.add(new ReportItem(421,"item name 2"));
report.add(new ReportItem(53,"item 3"));

Map beans = new HashMap();
beans.put("report", report);
XLSTransformer transformer = new XLSTransformer();

//transformer.groupCollection("report.rn");

transformer.transformXLS(templateFileName, beans, destFileName);

如何流式传输生成的文件(destFileName)而不将其保存到磁盘?

2 个答案:

答案 0 :(得分:0)

我认为您可以使用以下API来创建工作簿。它不会创建任何文件。

/**
 * Creates Workbook instance based on .xls template from a given InputStream and a number of beans
 *
 * @param is         xls InputStream with required
 * @param beanParams Beans in a map under keys used in .xls template to access to the beans
 * @return new {@link org.apache.poi.ss.usermodel.Workbook} generated by inserting beans into corresponding excel template
 * @throws net.sf.jxls.exception.ParsePropertyException if there were any problems in evaluating specified property value from a bean
 */
public org.apache.poi.ss.usermodel.Workbook transformXLS(InputStream is, Map beanParams) throws ParsePropertyException, InvalidFormatException {
    org.apache.poi.ss.usermodel.Workbook hssfWorkbook = null;
    try {
        hssfWorkbook = WorkbookFactory.create(is);
        transformWorkbook(hssfWorkbook, beanParams);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return hssfWorkbook;
}

答案 1 :(得分:0)

public void transformXLSToStream(String templateFileName, Map beans, java.io.OutputStream outputStream) 
  throws FileNotFoundException, InvalidFormatException,IOException {
    InputStream inputStream = new BufferedInputStream(new FileInputStream(templateFileName));

    XLSTransformer transformer = new XLSTransformer();
    org.apache.poi.ss.usermodel.Workbook workbook = transformer.transformXLS(inputStream, beans);

    workbook.write(outputStream);

    inputStream.close();
    outputStream.flush();
    outputStream.close();
}