mdenci
mdenci

Reputation: 307

Saving a file as CSV in Java (apache poi)

So, I have created an .xlsx file using apache-poi's XSSF model with all of the data I need in it, but the client wants exactly the same data with the same formatting (every value in it's own cell), only in a .csv file. So, I need the same file with a different file extension...

I've tried to just change the extension of the file from .xlsx to .csv, but upon opening it I get a warning saying that the "file format and extension don't match", but upon clicking "OK" the file opens without any errors or wrong data. Can I somehow save the XSSF model to be a .csv file without getting the mentioned error?

I've also tried to use the CSVPrinter from apache-commons, but it writes all of the data from one row into one cell (I know that .csv files are supposed to look like that, but the client wants what the client wants).

CSVPrinter part of the code:

    FileWriter out = new FileWriter("someFile.csv");
    CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.EXCEL);

    if (workbook != null) {
        XSSFSheet sheet1 = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet1.rowIterator();
        while (rowIterator.hasNext()) {
            Row row1 = rowIterator.next();
            Iterator<Cell> cellIterator = row1.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                csvPrinter.print(cell.getStringCellValue());
            }
            csvPrinter.println();
        }

    }
    csvPrinter.flush();
    csvPrinter.close();

This is called after creating and writing data in the XSSFWorkbook.

If I have to use the CSVPrinter to complete what I need to, is there a way to do that without creating the .xlsx file first (simply write the data in the desired format into a .csv file directly)?

Upvotes: 0

Views: 7349

Answers (1)

mdenci
mdenci

Reputation: 307

I've found a solution to my problem.

Instead of using CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.EXCEL); I've changed it to CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(';'));

For some reason (I would appreciate if someone can explain it to me), CSV file with a comma as a delimiter puts all of the data from one row into one cell, but when I put a semicolon as a delimiter, it works the way I want it to.

Upvotes: 1

Related Questions