How to read csv using column name in java

 

问题

https://stackoverflow.com/questions/59306694/how-to-read-csv-using-column-name-in-java

I have tried reading a column with its index using below code:

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;

for eg.

|HEADER 1| HEADER 2| HEADER 3|

|A|B|C|

|D| |F|

As I am passing col index in col1, but I am not able to store the column header text in variable to print that which column is having blank value.

Is there any way I can read the column to validate blank cells and then print the column name in result saying "This column is having blank cell and hence file is invalid"

In above table, How to read columns with its name. Say if I pass HEADER 2 it should read all the row data and if it finds blank field

解答

找出列数据中有空值的列名。用Java 实现代码较长。

Java 下的开源包 SPL 很容易写,只要 1 句:


A

1

=transpose(file("data.csv").import@w(;,";")).select(~.contain(null)).(~(1)/",This column is having blank cell and hence file is invalid")

SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为 validate.splx,在 Java 中以存储过程的方式调用脚本文件:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call validate()");
st.execute();

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集