ExAdmin v0.7.4 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 do
      column "Surname", fn c -> c.last_name end
      column "Given", fn c -> c.first_name end
      column "Category", fn c -> c.category.name end

      column "Groups", fn c -> 
        Enum.map(c.groups, &(&1.name))
        |> Enum.join("; ")
      end

      for label <- PhoneNumber.all_labels do
        column label, fn c -> 
          c.phone_numbers
          |> PhoneNumber.find_by_label(label)
          |> Map.get(:number, "")
        end
      end
    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

Summary

Macros

Configure a column in the exported CSV file

Customize the exported CSV file

Macros

column(field, fun)

Configure a column in the exported CSV file.

csv(list)

Customize the exported CSV file.