javaexcelapache-poifileoutputstreamxssf

How to write column by column data in Excel using Apache POI?


I want to write column by column to an Excel file but I don't know how to do this. Is it possible to make it? I looked in the docs and see no methods to write column by column. Here is my code:

private void writeColumnByColumn() throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet();
    String[] strings = {"a", "b", "c"};
    Row row = sheet.createRow(0);
    for (int i = 0; i < 3; i++) {
        // here i want to write "a" in the first column, "b" in the second and "c" in the third
    }
    
    FileOutputStream outputStream = new FileOutputStream("ok.xlsx");
    try (outputStream) {
        workbook.write(outputStream);
    }
}

Solution

  • This should do the work.

      private void writeColumnByColumn() throws IOException {
       XSSFWorkbook workbook = new XSSFWorkbook();
       XSSFSheet sheet = workbook.createSheet();
       String[] strings = {"a", "b", "c"};
       Row row = sheet.createRow(0);
       for (int i = 0; i < 3; i++) {
              Cell cell = row.createCell(i);
              cell.setCellValue(strings[i]);
       } 
     
       FileOutputStream outputStream = new FileOutputStream("ok.xlsx");
       try (outputStream) {
           workbook.write(outputStream);
       }
      }