使用SXSSFWorkbook创建具有多个工作表的Excel工作簿

时间:2016-04-10 17:11:22

标签: java excel apache-poi

我必须用两张表创建一个excel工作簿。我使用以下代码创建excel,然后下载它。但是,创建了第一张纸,但未创建第二张纸。我无法理解确切的原因。以下是我创建两张纸的部分。

import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private static final String SECOND_SHEET_NAME = "Sheet 2";

private static final String FIRST_SHEET_NAME = "Sheet 1"

protected Sheet firstSheet;
protected Sheet secondSheet;
protected Workbook outWorkbook;

//creating workbook
outWorkbook = new SXSSFWorkbook(1);
//create first sheet
firstSheet = outWorkbook.createSheet(FIRST_SHEET_NAME);

//create second sheet
secondSheet = outWorkbook.createSheet(SECOND_SHEET_NAME);
//setting the second sheet as unhidden

outWorkbook.setSheetHidden(outWorkbook.getSheetIndex(SECOND_SHEET_NAME), false);
try
{
   outWorkbook.write(outputStream);
}
catch(IOException)
{
    String errorMsg = "Failed to write to workbook";
    log.error(errorMsg, e);
}

1 个答案:

答案 0 :(得分:0)

问题是您没有在此处正确导出工作表。

outWorkbook.setSheetHidden(outWorkbook.getSheetIndex(SECOND_SHEET_NAME), 
false);
try
{
   outWorkbook.write(outputStream);
}
catch(IOException)
{
    String errorMsg = "Failed to write to workbook";
    log.error(errorMsg, e);
}

如果在创建所有工作表之前未调用dispose,则应写入工作表。这是一个我设法提供参考的例子。

static String outPath = "path";
static String fileName = "test.xlsx";

public static void main(String[] args) throws Throwable {

    ApacheExample1 a = new ApacheExample1();

    a.runExport("test");

}

private void runExport(String tag) throws IOException {
    SXSSFWorkbook wb = new SXSSFWorkbook();
    Sheet sh1 = wb.createSheet("Sheet" + 1);
    Sheet sh2 = wb.createSheet("Sheet" + 2);
    String[] v1 = {"test", "one"};
    String[] v2 = {"test", "two"};
    writeSXSSLRow(0, 0, sh1, v1);
    writeSXSSLRow(0, 0, sh2, v2);

    writeToFile(wb);

}

private static void writeToFile(SXSSFWorkbook wb) throws IOException {
    File f = new File(outPath);
    if (!f.exists()) {
        f.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(outPath + fileName);
    wb.write(out);
    out.close();

    //After everything is written, then we dispose the temp file.
    wb.dispose();
}

private static void writeSXSSLRow(int colStart, int cellRow, Sheet ws, String[] v) throws IOException {
    Row row = ws.createRow(cellRow);
    for (int col = colStart; col < colStart + v.length; col++) {
        Cell cell = row.createCell(col);
        cell.setCellValue(v[col - colStart]);
    }

}