I want to write data in a specific column based on the column header title and an attribute of the data to be written. For example, if I have 3 columns, first column with header title "aaa", second column with header title "bbb" and third column with header title "ccc". Then I have an object like this: Data data = new Data(int id, String header)
and the constructor set the attributes this.id = id
and this.header = header
... if the header is equals to "aaa" I want to write the data.id
in the column "aaa", if it is "bbb" in the "bbb", if it is "ccc" in the "ccc" column.
Here an example code:
private void writeInSpecificColumn(Data data) {
XSSFWorkbook wb = this.getWorkbook();
XSSFSheet st = this.getSheet();
if (data.header.equals("aaa")) {
// write data.id in the column with header "aaa"
} else if (data.header.equals("bbb")) {
// write data.id in the column with header "bbb"
} else {
// write data.id in the column with header "ccc"
}
}
Obviously, before doing this, I write the header columns in this way:
private void writeHeaders() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("ok");
Row row = sheet.createRow(0);
int counter = 1;
String[] headers = {"aaa", "bbb", "ccc"};
for (int i = 0; i < 3; i++) {
Cell cell = row.createCell(counter);
cell.setCellValue(headers[i]);
}
FileOutputStream outputStream = new FileOutputStream("ok.xlsx");
try (outputStream) {
workbook.write(outputStream);
}
workbook.close();
}