Reputation: 1473
I have created CSV file using Open CSV library using some run time data coming from different datasource.
Now I am looking a lot of empty columns which doesn't have value in column cells and so I want to delete that programmatically.
Approach I am currently trying to implement is, get first CSV data in String 2 dimensional array and iterate it vertically and do something to delete empty columns!
Is any other better approach I can follow? Pls suggest!
Regards
//edited
Code for writing in CSV using OpenCSV library:
public static void writeDataToCSV(CSVWriter writer, String[][] csvData){
List<String[]> csvDataList = new ArrayList<String[]>();
for (String[] rowData : csvData) {
csvDataList.add(rowData);
}
writer.writeAll(csvDataList);
}
Upvotes: 3
Views: 5212
Reputation: 2800
Did not actually run this, so some errors may exist, but the rough skeleton should be:
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
}
Upvotes: 0
Reputation: 15174
So in the provided String[]
, you know what index of the column you need to remove, correct? If so, you can do this:
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);
}
Upvotes: 1