需要在CSV文件中删除空列。

3
我使用OpenCSV库创建了CSV文件,其中包含来自不同数据源的某些运行时数据。
现在我发现有很多空列,这些列中没有值,因此我想以编程方式删除它们。
我目前正在尝试实现的方法是,获取第一个CSV数据的字符串二维数组,并在垂直方向上进行迭代,然后执行一些操作以删除空列!
是否有其他更好的方法?请建议!
谢谢。
//编辑
使用OpenCSV库写入CSV的代码:
public static void writeDataToCSV(CSVWriter writer, String[][] csvData){
    List<String[]> csvDataList = new ArrayList<String[]>();
    for (String[] rowData : csvData) {
        csvDataList.add(rowData);
    }
    writer.writeAll(csvDataList);
}

1
“删除”是什么意思? 是从2D字符串数组中删除还是从CSV文件中删除? - DeadlyJesus
我需要从CSV文件中删除空列! - S Singh
然后将其作为2D字符串数组读取,并重新编写CSV文件,不包括空列。 - DeadlyJesus
请在我的帖子中查找CSV写入代码的编辑! - S Singh
注意,您不能从列表中间删除条目,如果要在原地编辑它,则需要将其作为LinkedList的列表或数组。 - Konstantin Tarashchanskiy
显示剩余3条评论
2个回答

1
所以在提供的String[]中,你知道需要删除哪一列的索引,对吗?如果是这样,你可以这样做:
for (String[] rowData : csvData) {
    // Convert the String[] to an ArrayList to be able to easily remove the specific column
    ArrayList<String> rowArray = new ArrayList<String>(Arrays.asList(rowData));

    // Remove that specific column value
    rowArray.remove(<index of column>);

    // Convert the ArrayList back into an array so it can be written to the CSV
    String[] dataToWrite = rowArray.toArray(new String[rowArray.size()]);

    // Add it to the ArrayList of values to be written
    csvDataList.add(dataToWrite);
}

0

我并没有真正运行过这个程序,所以可能存在一些错误,但是大致的框架应该是:

int height;  //How many rows
int width;  //How many columns per row

Set<Integer> emptyCols = new HashSet<Integers>();  //Columns that are empty

for (int x = 0; x < width; x++) { //Look at each column
  boolean empty = true; //We have yet to find an item in this column
  for (int y = 0; y < height; y++) {
    if (!data[y][x].isEmpty()) {  //This column is not empty, we can move on
      empty = false;
      break;
    }
  }

  if (empty) {
    emptyCols.add(x);
  }
}

for (int y = 0; y < height; y++) {
  for (int x = 0; x < width; x++) {
    if (!emptyCols.contains(x)) {
      //write out data[y][x]
    }
  }
  //Terminate row
}

1
@Tom 谢谢你发现了那个。 - Konstantin Tarashchanskiy
你的最后一个 if 语句还缺少括号 :) - Ascalonian
@Ascalonian 我曾经是,现在不是了。谢谢你提醒。 - Konstantin Tarashchanskiy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接