【问题标题】:Apache CSV Reader: How to read CSV columns by header name?Apache CSV Reader:如何按标题名称读取 CSV 列?
【发布时间】:2019-11-15 08:16:43
【问题描述】:

我正在尝试读取 CSV 文件,我的方法是识别列标题并读取其中的数据。 apache 有一个库可以做到这一点。

下面是我的代码

public class CSVItemReader {

    private File file;

    public CSVItemReader(File file)
    {
        this.file = file;
    }

    public List<Item> readFile()
    {
        try
        {
            Reader reader = new FileReader(file);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
                      .withHeader("Unit of Measure","Item Description")
                    .withIgnoreHeaderCase()
                    .withTrim());
            int i=0;
            for (CSVRecord csvRecord : csvParser) {


                String itemDescription = csvRecord.get("Item Description");
                String itemName = csvRecord.get("Unit of Measure");

                System.out.println(itemName+" : "+itemDescription);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }
}

很遗憾,阅读器只能阅读第一个标题item description 下的项目。其余部分被忽略,只打印空白。

我的 CSV 文件也有点不同,它是直接从MS Excel 保存为.CSV 的文件。所以有空白列等。我不能保证第一列总是空白,第三列总是空白等等。这就是为什么我需要程序来识别列中的标题并读取其中的数据。

我还不得不说,我可以用index 很好地阅读它们。

以下是我的 CSV 示例。

,Item Description,,On Order,,BackOrd Qty,,On-hand Qty,,Item Name,,Vendor Name,,Active Price,,Item #,,Cost,,Avail Qty,,Department,,Attribute,,Size,,Margin %,,Ext Cost,,Ext Price,,Item Type,,Unit of Measure,,UPC,,Alternate Lookup,,Last Rcvd,,Reorder Point,,Regular Price,,Order Cost,,Margin,,Sale,,Wholesale,,MSRP,,1 Qty,,Custom price,,Dept Code,,Vendor Code,,Cust Ord Qty,,BackOrd Cost,,Last Sold,,Picture Assigned,,Manufacturer,,Shipping Weight,,Length,,Width,,Height,,Eligible for Rewards,,Creation Date,,Quick Pick Group,,Mobile,,

,Booster Pack ,,0,,0,,796,,83717845997,,,,1.99,,2977,,1.09,,796,,Financial Software,,,,,,45.1,,869.65,,"1,584.04",,Inventory,,,,0083733997,,08371734000,,9/26/2019,,0,,1.99,,1.07,,0.9,,1.79,,1.79,,0,,796,,1.79,,,,,,0,,0,,10/19/2019,,FALSE,,,,0,,0,,0,,0,,TRUE,,9/25/2019,,,,FALSE,,

请问我该如何解决这个问题?

【问题讨论】:

    标签: java csv filereader


    【解决方案1】:

    如果您希望保持简单并使用映射(以列名作为键,以列值作为值),那么您可以使用 CsvMapReader。 Super CSV 网站上有使用 CsvMapReader 进行读写的示例。

    写法很相似。

    `ICsvMapReader mapReader = new CsvMapReader(
          new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
     try {
      final String[] headers = mapReader.getHeader(true);
      Map<String, String> row;
      while( (row = mapReader.read(headers)) != null) {
        for (String header : headers) {
          System.out.println(header + " is " + row.get(header));
        }
      }
    } finally {
      mapReader.close();
    }`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2019-07-03
      • 2022-01-14
      • 1970-01-01
      • 2020-02-09
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多