CSV generation possible with Apache POI?

前端 未结 3 1682
礼貌的吻别
礼貌的吻别 2020-12-06 07:49

I need to generate csv files and I stumbled on a module in our project itself which uses Apache POI to generate excel sheets aleady. So I thought I could use the same to gen

3条回答
  •  独厮守ぢ
    2020-12-06 08:11

    Basic strategy:

    1) Apache Commons CSV is the standard library for writing CSV values.

    2) But we need to loop through the Workbook ourselves, and then call Commons CSV's Printer on each cell value, with a newline at the end of each row. Unfortunately this is custom code, it's not automatically available in XSSF. But it's easy:

            // In this example we construct CSVPrinter on a File, can also do an OutputStream
            Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
            CSVPrinter csvPrinter = new CSVPrinter(reader, CSVFormat.DEFAULT);              
    
            if (workbook != null) {
                XSSFSheet sheet = workbook.getSheetAt(0); // Sheet #0
                Iterator rowIterator = sheet.rowIterator();
                while (rowIterator.hasNext()) {               
                    Row row = rowIterator.next();
                    Iterator cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        csvPrinter.print(cell.getStringCellValue()); // Call Commons CSV here to print
                    }
                    // Newline after each row
                    csvPrinter.println();
                }
    
            }
            // at the end, close and flush CSVPrinter
            csvPrinter.flush();
            csvPrinter.close();
    

提交回复
热议问题