java - 通过分隔符解析时的值偏移
问题描述
在某些时候,列的值对我来说会发生变化。在附件中我把输入文件和解析后的输出文件
我首先使用了“,”形式的分隔符
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;
}
解决方案
推荐阅读
- javascript - 当工具提示出现时,顶部的 Chart.JS 值消失
- python - Use filename on dataframe and match it with another list and store the list element
- javascript - 最初不存在的 JQuery 选择元素
- javascript - 如何在 JavaScript ES6 中功能性地遍历矩阵?
- batch-file - 为什么即使启用延迟扩展后,变量名也不会被感叹号包围输出值?
- neural-network - “打破对称性”是什么意思?在神经网络编程的背景下?
- html - 将图像放入单元格中
- javascript - CKEditor 4 为链接添加新属性
- mysql - NodeJs MySQL 使用哈希密码登录
- python - 从 Python 访问 macOS 提醒