2

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();
}
GFriends
  • 35
  • 5
  • 1
    You could use a `HashMap` to keep track of the header value and the row number. Make it a class attribute (or constant) instead of using a `String[]` inside `writeHeaders()`, but use it there to write while using it somewhere else to lookup the row number. – deHaar Sep 01 '21 at 07:27

0 Answers0