Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to delete empty columns in csv

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);
}
like image 977
S Singh Avatar asked Feb 28 '26 15:02

S Singh


1 Answers

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);
}
like image 116
Ascalonian Avatar answered Mar 02 '26 05:03

Ascalonian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!