1
votes

I have the following code that reads a spreadsheet and writes to pipe-delimeted file. Rows have differing length. The last cell shouldn't get appended with a pipe character (but does). I tried things like https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum() but cannot make it work.

XSSFWorkbook wb = new XSSFWorkbook(pathandfilename);
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        XSSFSheet sheet = wb.getSheetAt(i);
        String outfilename = path + "\\" + prefix + sheetname + postfix;
        PrintWriter outfilewriter = new PrintWriter(outfilename, "UTF-8");
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                cell.setCellType(Cell.CELL_TYPE_STRING);
                outfilewriter.print(cell.getStringCellValue() + "|");
            }
            outfilewriter.print("\n");
        }
        outfilewriter.close();
    }
wb.close();
1

1 Answers

0
votes

I fixed it as such:

while (rowIterator.hasNext()) {    
Row row = rowIterator.next();
    List<String> recordArry = new ArrayList<String>();
    Iterator<Cell> cellIterator = row.cellIterator();
    while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        cell.setCellType(Cell.CELL_TYPE_STRING);
        recordArry.add(cell.getStringCellValue() + "|");
    }
    StringBuilder recordString = new StringBuilder();
    for (String elem : recordArry) {
        recordString.append(elem);
    }
    String recordString2 = StringUtils.chomp(recordString.toString(), "|");
    outfilewriter.print(recordString2);
    outfilewriter.print("\n");
}