Sample code for 30+ languages & platforms
Swift

CSV Insert Column

See more CSV Examples

Insert a new column into an existing CSV.

Note: This example requires Chilkat v9.5.0.89 or greater because the InsertColumn method was added in v9.5.0.89.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let csv = CkoCsv()!

    // Load the following CSV:

    //  Name;City;Weight
    //  John;Chicago;180
    //  Lisa;Denver;120

    // Indicate that the 1st line contains column names.
    csv.hasColumnNames = true
    success = csv.loadFile(path: "qa_data/csv/insertColumnTest.csv")

    // We can insert a column before the 1st column.
    csv.insertColumn(index: 0)

    print("\(csv.saveToString()!)")

    // The CSV now looks like this:

    //  ;Name;City;Weight
    //  ;John;Chicago;180
    //  ;Lisa;Denver;120

    // Set the cells in column 0.

    var col: Int = 0
    csv.setColumnName(index: col, columnName: "id")
    csv.setCell(row: 0, col: col, content: "100")
    csv.setCell(row: 1, col: col, content: "101")

    print("\(csv.saveToString()!)")

    // We now have:

    //  id;Name;City;Weight
    //  100;John;Chicago;180
    //  101;Lisa;Denver;120

    // Insert a new column between City and Weight
    // In other words, add a new column before the Weight column.
    var weightColumn: Int = csv.getIndex(columnName: "Weight").intValue
    print("Weight Column Index = \(weightColumn)")
    csv.insertColumn(index: weightColumn)

    print("\(csv.saveToString()!)")

    // We now have:

    //  id;Name;City;;Weight
    //  100;John;Chicago;;180
    //  101;Lisa;Denver;;120

    // Set the cells in the new column:

    csv.setColumnName(index: weightColumn, columnName: "Height")
    csv.setCell(row: 0, col: weightColumn, content: "6' 2\"")
    csv.setCell(row: 1, col: weightColumn, content: "5' 7\"")

    print("\(csv.saveToString()!)")

    // We now have:

    //  id;Name;City;Height;Weight
    //  100;John;Chicago;"6' 2""";180
    //  101;Lisa;Denver;"5' 7""";120

}