我使用 jxl 库创建了一个excel文件。代码工作正常,但唯一的问题是,每次从服务的动态值构建excel文件时,excel内容都会覆盖到 test.xls ,如下所示。有没有办法在内存中构建excel并传递字节以便下载它而不是创建外部文件(" test.xls ")
File file = new File("test.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
:
:
:
:
InputStream in = new FileInputStream(file);
if (in == null) {
out.close();
}
else
{
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
in.close();
out.close();
}
任何人都可以帮助我
答案 0 :(得分:5)
将ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableWorkbook workbook = Workbook.createWorkbook(baos);
// ...
workbook.close();
out.write(baos.toByteArray());
out.flush();
out.close();
与Workbook.createWorkbook(OutputStream os)
方法结合使用,在内存中创建工作簿,并将创建的字节数组转储到所需的输出流中。
WritableWorkbook workbook = Workbook.createWorkbook(out);
// ...
workbook.close();
out.flush();
out.close();
或者,您可以在不使用中间字节数组的情况下即时执行:
@Entity
@Table(name = "test")
public class Test {
@Id
private String testCode;
private String testName;
private int price;
public Test() {}
public Test(String testCode, String testName, int price) {
this.testCode = testCode;
this.testName = testName;
this.price = price;
}
public String getTestCode() {
return testCode;
}
public String getTestName() {
return testName;
}
public int getPrice() {
return price;
}
}
这种方法可能更好,因为JXL无论如何都要将工作簿保存在内存中,并且只在工作簿关闭时将其刷新到输出流。
答案 1 :(得分:4)
以下是使用POI创建excel并将其转换为字节的示例。
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
Row row = sheet.createRow(1);
Cell cell = row.createCell(cellnum++);
cell.setCellValue((String) obj);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
} catch (IOException e) {
} finally {
try {
bos.close();
workbook.close();
} catch (IOException e) {
}
}
byte[] bytes = bos.toByteArray();