我正在尝试读取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,,
我该如何解决?
[如果您希望保持简单,并使用地图(以列名作为键,并以列值作为值),则可以使用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();
}`