【问题标题】:Is there a way to put a custom separator for CSV file using CSVParser?有没有办法使用 CSVParser 为 CSV 文件添加自定义分隔符?
【发布时间】:2020-09-06 10:07:39
【问题描述】:

目前,我正在使用本教程介绍如何读取 CSV 文件:https://stackabuse.com/reading-and-writing-csvs-in-java-with-apache-commons-csv/ 它使用了 Apache-commons-csv 中的 CSVParser 和 CSVFormat。

它可以很好地阅读,但不是以我想要的方式。在我检查它为什么不起作用的原因后发现我的 CSV 文件有分隔符“|”而不是 "," 并且 CSVParser 无法读取它。有没有办法让我将 CSVParser 的分隔符更改为“|”代替 ”,”?我真的很想使用这种方法,因为record.get("name of the map") 确实对我正在做的这个项目有很大帮助,我不想手动更改 CSV 文件。

这是我当前的代码:

@PostMapping("/uploadFile")
    public static void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException{
        if(file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
            InputStreamReader input = new InputStreamReader(file.getInputStream());
            CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
            for (CSVRecord record : csvParser) {
                System.err.println(record.get("nameOftheColumn"));
            }
            response.sendRedirect("/rekonsiliasi");
        }
        else {
            response.sendRedirect("/rekonsiliasi");
        }
    }

感谢任何形式的帮助。

【问题讨论】:

    标签: java csv apache-commons-csv


    【解决方案1】:

    你尝试过使用

    CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().withDelimiter('|').parse(input);
    

    相关 JavaDoc 见http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withDelimiter-char-

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 2011-06-24
      • 2012-11-03
      相关资源
      最近更新 更多