我需要一些帮助。我想实现一个代码,希望在其中读取csv文件中的数据。
示例CSV文件(details.csv):
id,名称,年龄
1,bh,23
2,nit,24
我想在Java中创建这样的方法来读取此CSV,我将工作表名称,列名称和行名称作为参数传递。只要有此组合的匹配项,就会选择相应的数据。
示例:-我想传递details.csv,name和1。我应该将输出作为bh。
您能帮我吗?
我尝试使用以下代码,但返回空值:-
public static String searchCsvLine(String filename, String searchString, String rowname) throws IOException {
String resultRow = null;
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ( (line = br.readLine()) != null ) {
String[] values = line.split(",");
if(values.equals(searchString)) {
resultRow = line;
break;
}
}
br.close();
return resultRow;
}
答案 0 :(得分:0)
您应该解析csv文件的第一行以获取列名。
public class Test {
public static String searchCsvLine(String filename, String columnName, String rowName) throws IOException {
String resultRow = null;
BufferedReader br = new BufferedReader(new FileReader(filename));
// parse first line as column names
String line = br.readLine();
String[] columns = line.split(",");
int columnIndex = -1;
for (int i = 0; i < columns.length; i++) {
if (columnName.equals(columns[i])) {
columnIndex = i;
break;
}
}
// read lines to match row
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
if (rowName.equals(values[0])) {
// return value at columnIndex
resultRow = values[columnIndex];
break;
}
}
br.close();
return resultRow;
}
public static void main(String[] args) throws IOException {
String name = searchCsvLine("details.cvs", "name", "1");
System.out.println("name is " + name);
}
}
答案 1 :(得分:0)
尝试以下方法:
public static String searchCsvLine(String filename, String searchString,String rowname) throws IOException {
String resultRow = null;
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
int searchStringIndex=0;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//get index of searchString
for (int i = 0; i < values.length; i++) {
if(values[i].equalsIgnoreCase(searchString)){
searchStringIndex=i;
break;
}
}
//get required rowname
for (int i = 0; i < Integer.parseInt(rowname); i++) {
line=br.readLine();
}
//split the line found by rowname and get value as per searchString index (given column)
values = line.split(",");
resultRow=values[searchStringIndex];
break;
}
br.close();
System.out.println(resultRow);
return resultRow;
}
}