2015-01-15 82 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); 
}