首页 > 解决方案 > 冲刺启动中的多个 Excel 文件

问题描述

在此处输入图像描述有没有办法通过spring boot创建多个excel文件而不是多个工作表?我一直在使用 apache poi 来生成 excel。

@GetMapping("/export/excel")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        String headerKey = "Content-Disposition";
        String headervalue = "attachment; filename=Customer.xlsx";
        response.setHeader(headerKey, headervalue);
        List<cusEntity> data1= customerRepo.fetchEmailData();
        UserExcelExporter exp = new UserExcelExporter(data1);
        exp.export(response);
}

public class UserExcelExporter {
    private XSSFWorkbook workbook;
    private XSSFSheet sheet;
    private List<EmailDataEntity> listClients;

public UserExcelExporter(List<cusEntity> listClients) {
    this.listClients=listClients;
    workbook = new XSSFWorkbook();
}

private void createCell(Row row, int columnCount, Object value, CellStyle style) {
    sheet.autoSizeColumn(columnCount);
    Cell cell=row.createCell(columnCount);
    if(value instanceof Long) {
        cell.setCellValue((Long) value);
    }else if(value instanceof Integer) {
        cell.setCellValue((Integer) value);
    }else if(value instanceof Boolean) {
        cell.setCellValue((Boolean) value);
    }else {
        cell.setCellValue((String) value);
    }
    cell.setCellStyle(style);
}

private void writeHeaderLine(String iteration) {
        sheet = workbook.createSheet("Report");
        Row row = sheet.createRow(0);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        createCell(row,0,"Trust & Agency Service",style);
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,6));
        font.setFontHeightInPoints((short)(10));
    }

private void writeDataLines() {
    int rowCount=1;
    CellStyle style=workbook.createCellStyle();
    XSSFFont font=workbook.createFont();
    font.setFontHeight(14);
    style.setFont(font);
    for(cusEntity client:listClients) {
        Row row=sheet.createRow(rowCount++);
        int columnCount=0;
        createCell(row, columnCount++, client.getname(), style);
    }
}

public void export(HttpServletResponse response,String iteration) throws IOException{
    writeHeaderLine(iteration);
    writeDataLines();
    ServletOutputStream outputStream=response.getOutputStream();
    workbook.write(outputStream);
    workbook.close();
    outputStream.close();
}

}

当我尝试重复 exp.export(response) 的代码时,它给了我 1 个 excel,对于下一个 excel,它说工作簿已经包含一个名为“报告”的工作表。我认为如果它创建了 2 个 excel,那么具有相同的工作表名称应该不是问题。但似乎它试图创建另一个工作表而不是另一个 excel 。如果我错了,请纠正我。

感谢团队。

标签: javaexcelspring-bootapache-poi

解决方案


我这样做的方法是更改​​输出流:并从 HomeController 传递文件名

OutputStream outputStream = new FileOutputStream(String.format("C:\\Users\\kasis\\ExcelFolder\\%s.xlsx",fileName));

推荐阅读