Lua Requires Chilkat v9.5.0.89+
Lua
CSV Insert Column
See more CSV Examples
Insert a new column into an existing CSV.Chilkat Lua Downloads
local chilkat = require("chilkat")
local 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.has_column_names = true
local success = csv:load_file("qa_data/csv/insertColumnTest.csv")
-- We can insert a column before the 1st column.
csv:insert_column(0)
print(csv:save_to_string())
-- The CSV now looks like this:
-- ;Name;City;Weight
-- ;John;Chicago;180
-- ;Lisa;Denver;120
-- Set the cells in column 0.
local col = 0
csv:set_column_name(col, "id")
csv:set_cell(0, col, "100")
csv:set_cell(1, col, "101")
print(csv:save_to_string())
-- 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.
local weightColumn = csv:get_index("Weight")
print("Weight Column Index = " .. weightColumn)
csv:insert_column(weightColumn)
print(csv:save_to_string())
-- We now have:
-- id;Name;City;;Weight
-- 100;John;Chicago;;180
-- 101;Lisa;Denver;;120
-- Set the cells in the new column:
csv:set_column_name(weightColumn, "Height")
csv:set_cell(0, weightColumn, "6' 2\"")
csv:set_cell(1, weightColumn, "5' 7\"")
print(csv:save_to_string())
-- We now have:
-- id;Name;City;Height;Weight
-- 100;John;Chicago;"6' 2""";180
-- 101;Lisa;Denver;"5' 7""";120