Return byte[] 工作簿中的特定 sheet

Return particular sheet from Workbook in byte[]

我将此 excel 工作簿存储在我的资源文件夹中。考虑到这个 excel 有 9 页,我想提取一个特定的页面并将其 return 放入 byte[].

我创建了这个控制器

@GetMapping(value = "/getSinglePage/{pageNumber}")
    private ResponseEntity<byte[]> getExcelByPageNumber(@PathVariable Integer pageNumber) throws IOException {
        return new ResponseEntity<>(service.getExcelByPageNumber(pageNumber), HttpStatus.OK);
    }

服务代码包含--

public byte[] getExcelByPageNumber(Integer pageNumber) throws IOException {
        
        Workbook workbook = null;
        byte[] byteArray = null;
        // here file.xls is my excel sheet that contains 9 sheet for example

        workbook = WorkbookFactory.create(loader.getResource("classpath:file.xls").getInputStream());
        //gets the sheet from given page number 
        Sheet sheet = workbook.getSheetAt(pageNumber);
    
        // now i want to return this sheet in the form of byte[]
        return byteArray;
    }

我应该如何return把它变成byte[]的形式?

通过做一些 POC,我了解到一个作品sheet 没有自己的工作簿就不可能存在。 Workbook 限制了图书馆的工作。所以显然我找不到任何直接的解决方案来复制或附加 sheet.

我所做的是删除不需要的 sheets,它们只在工作簿中保留 sheet,然后使用 ByteArrayOutputStream 写入它。

 public byte[] getExcelByPageNumber(Integer pageNumber) throws IOException {
        // TODO Auto-generated method stub
        Workbook workbook = new XSSFWorkbook();
        workbook = WorkbookFactory.create(loader.getResource("classpath:file.xls").getInputStream());
        Sheet tmpSheet = workbook.getSheetAt(pageNumber - 1);
        for (int i = workbook.getNumberOfSheets() - 1; i >= 0; i--) {

            String sheetName = workbook.getSheetName(i).trim();

            if (!tmpSheet.getSheetName().equals(sheetName)) {
                workbook.removeSheetAt(i);
            }

        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            workbook.write(bos);
        } finally {
            bos.close();
        }
        byte[] bytes = bos.toByteArray();
        return bytes;

    }