IS there the way to create multiple excel file instead of multiple worksheets through spring boot?
I have been using apache poi for generation of excel.
JavaScript
x
@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);
}
JavaScript
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();
}
}
When i try to repeat the code of exp.export(response) , it gives me the 1 excel and for the next excel it says The workbook already contains a sheet named ‘Report’. I thought that if it created 2 excel then having the same worksheet name should not have been the issue . But seems like its trying to create another sheet instead of another excel . Correct me if I am wrong .
Thanks Team.
Advertisement
Answer
The way I did it was by changing the output stream: And passing fileName from the HomeController
JavaScript
OutputStream outputStream = new FileOutputStream(String.format("C:\Users\kasis\ExcelFolder\%s.xlsx",fileName));