首页 > 解决方案 > 如何在java中使用列名读取csv

问题描述

我尝试使用以下代码读取带有索引的列:

    int col1;
    String msg = null;
    int i = 0;
    String[] array = null;

    File file = new File(csvFileName);

    List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

    for (String line : lines) {
        array = line.split(";", -1);
        // System.out.println(array[col1]);
        if (array[col1].equals("")) {
            // System.out.println("Cell is blank");
            break;

        } else {
            // System.out.println(array[col1].toString());
            i++;
        }

    }
    if (i < (array[col1].length())) {
        msg = "Invalid file";
        // System.out.println("Invalid File");
    } else {
        msg = "Valid file";
        // System.out.println("valid File");
    }

    return msg;

例如。

|HEADER 1| HEADER 2| HEADER 3|
|A|B|C|
|D| |F|

当我在 col1 中传递 col 索引时,我无法将列标题文本存储在变量中以打印哪个列具有空白值。

有什么方法可以读取列以验证空白单元格,然后打印列名,结果显示“此列有空白单元格,因此文件无效”

在上表中,如何使用其名称读取列。假设我通过 HEADER 2 它应该读取所​​有行数据并且如果它找到空白字段

标签: javacsv

解决方案


根据您的输入数据示例:

|HEADER 1| HEADER 2| HEADER 3|
|A|B|C|
|D| |F|

所以你有一个由 ha 标题行组成的文件,其中有你的列名和数据。

要读取 colimns 名称,您需要以不同的方式解析第一行:

// field separator
String separator = ";";

//...
int i = 0;

Map<String, int> headers = new HashMap<>();

for (String line : lines) {
    if (i == 0) {
        String[] headLine = line.split(separator);
        for (int j = 0; j < headLine.length; j++) {
            headLine.put(headLine[j], j);
        }
        i++;
        continue;
    }
}

因此,您将每个列名放在地图中并保存列的索引。

地图的大小也是行 len 以检查您是否阅读了所有预期的字段。

然后你读取数据:

int col1 = 1; // assign a valid column index
int fields = 0;

for (String line : lines) {

    if (array[col1].equals("")) {
        // System.out.println("Cell is blank");
        break;
    } else {
        // System.out.println(array[col1].toString());
        fields++;
    }
}

if (fields < headers.size()) {
    msg = "Invalid file";
    // headers[fields] is the name of the column with the empty cell 
}

在您的示例col1中,索引不是列的名称,但您从未使用值设置它,也许这是问题之一。


推荐阅读