ExAdmin v0.8.3-build.2 ExAdmin.CSV
ExAdmin provides a CSV export link on the index page of each resource.
The CSV file format can be customized with the csv
macro.
For example, give the following ecto model for Example.Contact:
defmodule Example.Contact do
use Ecto.Model
schema "contacts" do
field :first_name, :string, default: ""
field :last_name, :string, default: ""
field :email, :string, default: ""
belongs_to :category, Example.Category
has_many :contacts_phone_numbers, Example.ContactPhoneNumber
has_many :phone_numbers, through: [:contacts_phone_numbers, :phone_number]
has_many :contacts_groups, Example.ContactGroup
has_many :groups, through: [:contacts_groups, :group]
end
...
end
The following resource file will export the contact list as shown below:
defmodule Example.ExAdmin.Contact do
use ExAdmin.Register
alias Example.PhoneNumber
register_resource Example.Contact do
csv [
{"Surname", &(&1.last_name)},
{:category, &(&1.category.name)},
{"Groups", &(Enum.map(&1.groups, fn g -> g.name end) |> Enum.join("; "))},
] ++
(for label <- PhoneNumber.all_labels do
fun = fn c ->
c.phone_numbers
|> PhoneNumber.find_by_label(label)
|> Map.get(:number, "")
end
{label, fun}
end)
end
end
# output.csv
Surname,Given,Category,Groups,Home Phone,Business Phone,Mobile Phone
Pallen,Steve,R&D,Groop 1;Groop2,555-555-5555,555,555,1234
The macros available in the csv do block include
column
- Define a column in the exported CSV file
Examples
# List format
csv [:name, :description]
# List format with functions
csv [:id, {:name, fn item -> "Mr. " <> item.name end}, :description]
# No header
csv header: false do
column :id
column :name
end
# Don't humanize the header name
csv [:name, :created_at], humanize: false
Summary
Functions
Macros
Configure a column in the exported CSV file.
Examples
csv do
column :id
column :name, fn user -> "#{user.first_name} #{user.last_name}" end
column :age
end