Import and Export CSV file in Phoenix Elixir using csv plugin

Hi. I’m seeking for help of how i can work with decoding and encoding (export & import) of CSV file in Elixir? Thanks a lot. Your help is highly appreciated.

4 Likes

I have used the csv library. There are several others if you search for “csv” at hex

Search Results

Do you have specific needs?

1 Like

Yeah, that’s also the library that I’m using.

My question is, how can i start to my project? how can i export and import a csv file and also how can i populate it in the database? Just a newbie here btw. Thanks.

1 Like

I use something like this to read in a CSV file:

@doc """
returns a sorted list of name for each person in
order of preference
"""
File.stream!("filename.csv") 
|> CSV.decode(headers: true)
|> Enum.group_by(&(&1["ID"]))
|> Enum.map(&get_first/1)
|> Enum.reduce(%{},&Enum.into/2)

for writing, you would use CSV.encode/2 adding a File.write/3 to the end.

Database population is a different animal. I don’t have anything to share off-hand, but hopefully someone else will jump in.

2 Likes

Thanks @ejc123! Where should i put those codes? should i create another controller for the csv? I swear, i don’t know what to do.

1 Like

I swear, i don’t know what to do

Well, what are you trying to do? Load the data once as sort of seed data for development? Let people submit CSV files over the web and load them into the database?

1 Like

Hi @benwilson512. Yes, that’s what I’m trying to do. But yeah, i really don’t know how to start. Please help me. Thanks.

1 Like

Happy to help, but I gave you two very different options. Do you want to do all of them? Just some of them? You didn’t indicate which.

1 Like

I’m trying to do the second option.

1 Like

https://github.com/beatrichartz/csv

How can I implement this plugin into my project?

Thanks.

1 Like

The github page you linked to has instructions for adding it to your project. If you aren’t clear on how to add dependencies to mix you may want to consider checking out the getting started guides on the elixir-lang.org website.

1 Like

Hi, already add the csv dependencies to my project, and problem now is the next step. Should i generate another controller, view, model for this? where should i place those codes in my project?

1 Like