【问题标题】:Need to delete empty columns in csv需要删除csv中的空列
【发布时间】:2015-01-15 15:32:03
【问题描述】:

我使用来自不同数据源的一些运行时数据使用 Open CSV 库创建了 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);
}

【问题讨论】:

  • “删除”是什么意思?从 2D 字符串数组或 csv 文件中删除它们?
  • 我需要从 CSV 中删除空列!
  • 然后将其读取为二维字符串数组,并在不包括空列的情况下重写 csv。
  • 您能否添加用于编写 CSV 文件的代码 (CSVWriter)?
  • 在我的帖子中找到编辑 csv 写代码!

标签: java arrays csv opencsv


【解决方案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);
}

【讨论】:

    【解决方案2】:

    并没有实际运行这个,所以可能存在一些错误,但粗略的骨架应该是:

    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
    }
    

    【讨论】:

    • @Tom 感谢您了解这一点
    • 你最后的if 语句仍然缺少括号:)
    • @Ascalonian 我是,现在不是。谢谢你的收获。
    猜你喜欢
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2013-10-02
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多