I need to write 3 different sheets in the same excel workbook in JAVA. I need to segregate this task to 3 different classes, each class should write one excel sheet in the same file. Now everytime at the end of a class, I need to flush the data to that particular sheet. Something like,
inputStream =new FileInputStream("FileName.xls");
wb_template = new XSSFWorkbook(inputStream);
inputStream.close();
wb = new SXSSFWorkbook(wb_template);
//Logic here
FileOutputStream out = new FileOutputStream("FileName.xls");
workbook.write(out);
wb.dispose();
out.close();
and repeat this common part of opening and closing in another class for another sheet.
Now, as my class is annotated with @Component
annotation, I simply can not create FileOutputStream
with new in my classes as the sample code above.
So I need to create bean for them. So now my doubt is, how many beans do I need to create for each type. i.e FileInputStream
, SXSSFWorkbook
and FileOutputStream
? As I need to dispose workbook at end of every class and need to close FileOutputStream
at end of every class, will single bean be sufficient ???
I am novice to this field. Any lead will be appreciated.
I don't think input and output streams are good candidates for Spring beans.
Much better and more intuitive candidates are your excel sheet writers:
interface ExcelSheetWriter {
void writeOneSheet(String excelFileName);
}
@Configuration
class Config {
@Bean(name="sheet1Writer) ExcelWriter getSheet1Writer() {
return new Sheet1Writer(); //implements ExcelWriter
}
}
class ExcelDocumentWriter {
@Autowired @Qualifier("sheet1Writer") ExcelWriter sheet1Writer;
@Autowired @Qualifier("sheet2Writer") ExcelWriter sheet2Writer;
@Autowired @Qualifier("sheet3Writer") ExcelWriter sheet3Writer;
//... use them to write the entire document
}
Good spring beans don't change state after initialization.