gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:57 26 4
gpt4 key购买 nike

我必须创建一个包含两张表的 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);
}

最佳答案

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

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]);
}

}

关于java - 使用 SXSSFWorkbook 创建具有多个工作表的 Excel 工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36532868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com