2015-01-15 68 views
1

我已经使用Open CSV库使用来自不同数据源的一些运行时数据创建了CSV文件。需要删除csv中的空列

现在我正在寻找很多空列,它们在列单元格中没有值,所以我想以编程方式删除它。

方法我目前试图实现的是,获取字符串2维数组中的第一个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 String数组或从csv文件中删除它们? – DeadlyJesus 2015-01-15 15:34:32

+0

我需要从CSV中删除空列! – 2015-01-15 15:35:53

+0

然后将其作为二维字符串数组读取,并在不包含空列的情况下重写csv。 – DeadlyJesus 2015-01-15 15:37:45

回答

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感谢您的支持 – 2015-01-15 16:49:45

+0

您最近的'if'语句仍然缺少圆括号:) – Ascalonian 2015-01-15 16:54:50

+0

@Ascalonian我是,现在我不是。谢谢你的收获。 – 2015-01-15 17:05:59

1

所以在提供的String[]中,y你知道你需要删除的列的索引是否正确?如果是这样,你可以这样做:

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); 
}