Rust
Rust
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 Rust Downloads
let csv = chilkat::Csv::new();
// Load the following CSV:
// Name;City;Weight
// John;Chicago;180
// Lisa;Denver;120
// Indicate that the 1st line contains column names.
csv.set_has_column_names(true);
let _ = csv.load_file("qa_data/csv/insertColumnTest.csv").is_ok();
// We can insert a column before the 1st column.
let _ = csv.insert_column(0);
println!("{}", csv.save_to_string().unwrap_or_default());
// The CSV now looks like this:
// ;Name;City;Weight
// ;John;Chicago;180
// ;Lisa;Denver;120
// Set the cells in column 0.
let col = 0;
let _ = csv.set_column_name(col, "id");
let _ = csv.set_cell(0, col, "100");
let _ = csv.set_cell(1, col, "101");
println!("{}", csv.save_to_string().unwrap_or_default());
// 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.
let weight_column = csv.get_index("Weight");
println!("Weight Column Index = {}", weight_column);
let _ = csv.insert_column(weight_column);
println!("{}", csv.save_to_string().unwrap_or_default());
// We now have:
// id;Name;City;;Weight
// 100;John;Chicago;;180
// 101;Lisa;Denver;;120
// Set the cells in the new column:
let _ = csv.set_column_name(weight_column, "Height");
let _ = csv.set_cell(0, weight_column, "6' 2\"");
let _ = csv.set_cell(1, weight_column, "5' 7\"");
println!("{}", csv.save_to_string().unwrap_or_default());
// We now have:
// id;Name;City;Height;Weight
// 100;John;Chicago;"6' 2""";180
// 101;Lisa;Denver;"5' 7""";120