首页 > 解决方案 > 通过分隔符解析时的值偏移

问题描述

在某些时候,列的值对我来说会发生变化。在附件中我把输入文件和解析后的输出文件

输入文件

解析后

我首先使用了“,”形式的分隔符

 private static List<Row> getCsvRow(Path csvPath) {
    try(Stream<String> lines = Files.lines(csvPath)) {
      return lines
          .map(str -> str.split(","))
          .map(Converter::mapCvsRow)
          .collect(Collectors.toUnmodifiableList());
    } catch (Exception e) {
      return Collections.emptyList();
    }
  }
 try(var outputStream = Files.newOutputStream(excelPath)) {
      workbook.write(outputStream);
    } catch (Exception e) {
      e.printStackTrace(); 
    }

然后我做到了,但它仍然导致我移动列中的数据

 private void csvToXlsx(Path csvFilePath, Path excelFilePath) throws Exception {
        logger.info("Converting CSV to XLSX" + excelFilePath);
        List<CSVRecord> records = collectAllEntries(csvFilePath);
        XSSFWorkbook myWorkBook = new XSSFWorkbook();
        FileOutputStream writer = new FileOutputStream(new File(excelFilePath.toString()));
        XSSFSheet mySheet = myWorkBook.createSheet();
        IntStream.range(0, records.size())
                .forEach(rowNum -> {
                    XSSFRow myRow = mySheet.createRow(rowNum);
                    CSVRecord record = records.get(rowNum);
                    for (int i = 0; i < record.size(); i++) {
                        XSSFCell myCell = myRow.createCell(i);
                        myCell.setCellValue(record.get(i));
                    }
                });
            myWorkBook.write(writer);
            writer.close();
        }

我也有这个方法

 public List<CSVRecord> collectAllEntries(Path path) throws IOException {
        List<CSVRecord> store = new ArrayList<>();
        try (
                Reader reader = Files.newBufferedReader(path);
                CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL)
        ) {
            for (CSVRecord csvRecord : csvParser) {
                store.add(csvRecord);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        return store;
    }

标签: javaparsing

解决方案


推荐阅读