Apache POI 查找行中的最后一个单元格
Apache POI find last cell in row
我有以下代码读取电子表格并写入管道分隔文件。行有不同的长度。最后一个单元格不应附加管道字符(但确实如此)。我尝试了 https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum() 之类的方法,但无法正常工作。
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();
我是这样修复的:
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");
}
我有以下代码读取电子表格并写入管道分隔文件。行有不同的长度。最后一个单元格不应附加管道字符(但确实如此)。我尝试了 https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum() 之类的方法,但无法正常工作。
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();
我是这样修复的:
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");
}